lenapi 0.1.4.4__tar.gz → 0.1.4.5__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/PKG-INFO +5 -1
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/README.md +4 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/__init__.py +1 -1
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/application.py +5 -1
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/background.py +62 -3
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/cli.py +5 -0
- lenapi-0.1.4.5/lenapi/migration_render.py +25 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/models.py +14 -2
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi.egg-info/PKG-INFO +5 -1
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi.egg-info/SOURCES.txt +2 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi_bootstrap.py +6 -1
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/pyproject.toml +1 -1
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/tests/test_framework_features.py +26 -0
- lenapi-0.1.4.5/tests/test_migration_render.py +48 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/tests/test_project_isolation.py +44 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/LICENSE +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/admin.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/auth.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/authentication.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/authorization.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/concurrency.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/database.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/dependencies.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/docs_guard.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/logging.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/middleware.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/model.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/mongodb.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/openapi.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/parameters.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/project.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/request.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/response.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/security.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/security_store.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/sentinels.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/service.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/throttling.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi/transaction.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi.egg-info/dependency_links.txt +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi.egg-info/entry_points.txt +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi.egg-info/requires.txt +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/lenapi.egg-info/top_level.txt +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/setup.cfg +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/tests/test_admin_console.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/tests/test_cli_settings_recovery.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/tests/test_docs_guard.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/tests/test_media_upload.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/tests/test_mongodb.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/tests/test_platform_services.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/tests/test_security_patch.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/tests/test_sentinels.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/tests/test_throttle.py +0 -0
- {lenapi-0.1.4.4 → lenapi-0.1.4.5}/tests/test_user_model_extension.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: lenapi
|
|
3
|
-
Version: 0.1.4.
|
|
3
|
+
Version: 0.1.4.5
|
|
4
4
|
Summary: A modern ASGI framework with Pydantic validation, sync and async database access, WebSockets, authentication, and integrated API documentation.
|
|
5
5
|
Author: Maekandex Communication Limitation
|
|
6
6
|
Author-email: "Ifeanyi M. Onovo" <ifeanyi@maekandex.com.ng>
|
|
@@ -531,6 +531,8 @@ python lenora.py run
|
|
|
531
531
|
|
|
532
532
|
Use the installed `lenora` command to create the first project; `python lenora.py ...` commands are available after entering the generated project. The server listens on `127.0.0.1:8009` by default. The generated application contains `app/models.py`, `app/schemas.py`, `settings.py`, `main.py`, a `tests/` package, a project-local CLI launcher, `alembic.ini`, and a `migrations/` folder. The default `User` model and authentication implementation live in the framework. The initial migration includes the framework's `User` table automatically. `LENAPI()` sets up `app.authenticator` from `settings.AUTHENTICATION`, but route protection is opt-in: pass an authenticator to `LENAPI(auth=...)`, `Router(auth=...)`, or a route's `auth=` parameter. This keeps login and registration routes public unless you protect them too. The framework repository contains the installable `lenapi` package; create an application scaffold separately with `lenora startproject`.
|
|
533
533
|
|
|
534
|
+
Generated `main.py` creates the configured application before importing project models or routers. This order sets `PROJECT_NAMESPACE` before SQLAlchemy declares model tables and lets you run the generated app directly with Uvicorn, for example `uvicorn main:app --host 0.0.0.0 --port 8010`. Keep `create_app(__file__, __package__)` above imports that load `app.models`; otherwise Uvicorn may load unprefixed table names that do not match the namespaced tables created by migrations.
|
|
535
|
+
|
|
534
536
|
If `settings.py` is accidentally deleted, run `python lenora.py repair-settings` from the project directory. It recreates the generated defaults only when the file is missing and refuses to overwrite an existing settings file. The recreated file gets fresh `SECRET_KEY` and `API_KEY` values; review it before starting the app. The old `SECRET_KEY` cannot be recovered, so tokens signed with that key will no longer validate.
|
|
535
537
|
|
|
536
538
|
Run `python lenora.py apikey` inside a project to set `AUTHENTICATION = "api_key"`, add the `APIKey` model to `app/models.py` when it is missing, and run the migration workflow. The command is safe to repeat; it leaves an existing model in place and applies no migration when the database is already current. **The built-in API-key authenticator uses the framework `User` model.** It hashes the presented key and compares it with the digest in `User.api_key`; `register_user(..., authentication="api_key")` writes that digest and returns the raw key once. The generated `APIKey` table is a separate, optional app-managed key registry, linked to `User` by `user_id`; the default authenticator and `register_user()` do not automatically read or populate it. If your app wants that table to be the authentication lookup source, implement and configure that lookup explicitly. Never store raw keys in `key_hash`.
|
|
@@ -1632,6 +1634,8 @@ class User(BaseUser):
|
|
|
1632
1634
|
|
|
1633
1635
|
Import the extended `User` from `app.models` in application code and run `python lenora.py migration`. Do not set a second table name for this subclass; it extends the framework's existing `user` table. `bio` is nullable because MySQL does not support defaults on `TEXT` columns; if existing rows need an empty string instead of `NULL`, add a data backfill to the generated migration. Ordinary subclasses of the abstract `Model` base still get a table inferred from their class name.
|
|
1634
1636
|
|
|
1637
|
+
LenAPI preserves Boolean server defaults as Boolean literals in generated migrations so a revision created with SQLite can also apply on PostgreSQL. For an already-generated revision that contains `server_default=sa.text('0')` on a Boolean column, update it to `server_default=sa.false()` before applying it to PostgreSQL.
|
|
1638
|
+
|
|
1635
1639
|
For API-key mode, call `register_user(data=..., authentication="api_key")` from your own registration route. It generates a URL-safe key with 32 bytes of cryptographically secure randomness and returns it once as plain text. LenAPI stores only its SHA-256 digest in the nullable `user.api_key` column, so the original key cannot be recovered later. Send the returned key on authenticated requests with `X-API-Key: <key>`. The `python lenora.py apikey` command also creates an `APIKey` table for app-managed key records, but the built-in authenticator looks up `User.api_key`; the helper does not automatically add rows to that separate table.
|
|
1636
1640
|
|
|
1637
1641
|
Use `register_user()` from your own registration handler if you want the framework's user creation and password handling. The password encoding uses Django's `pbkdf2_sha256` format, so Django's password hashers can verify it; this is one-way hashing, not reversible encryption. See [Django password management](https://docs.djangoproject.com/en/6.0/topics/auth/passwords/) for the encoded format and verification helpers.
|
|
@@ -479,6 +479,8 @@ python lenora.py run
|
|
|
479
479
|
|
|
480
480
|
Use the installed `lenora` command to create the first project; `python lenora.py ...` commands are available after entering the generated project. The server listens on `127.0.0.1:8009` by default. The generated application contains `app/models.py`, `app/schemas.py`, `settings.py`, `main.py`, a `tests/` package, a project-local CLI launcher, `alembic.ini`, and a `migrations/` folder. The default `User` model and authentication implementation live in the framework. The initial migration includes the framework's `User` table automatically. `LENAPI()` sets up `app.authenticator` from `settings.AUTHENTICATION`, but route protection is opt-in: pass an authenticator to `LENAPI(auth=...)`, `Router(auth=...)`, or a route's `auth=` parameter. This keeps login and registration routes public unless you protect them too. The framework repository contains the installable `lenapi` package; create an application scaffold separately with `lenora startproject`.
|
|
481
481
|
|
|
482
|
+
Generated `main.py` creates the configured application before importing project models or routers. This order sets `PROJECT_NAMESPACE` before SQLAlchemy declares model tables and lets you run the generated app directly with Uvicorn, for example `uvicorn main:app --host 0.0.0.0 --port 8010`. Keep `create_app(__file__, __package__)` above imports that load `app.models`; otherwise Uvicorn may load unprefixed table names that do not match the namespaced tables created by migrations.
|
|
483
|
+
|
|
482
484
|
If `settings.py` is accidentally deleted, run `python lenora.py repair-settings` from the project directory. It recreates the generated defaults only when the file is missing and refuses to overwrite an existing settings file. The recreated file gets fresh `SECRET_KEY` and `API_KEY` values; review it before starting the app. The old `SECRET_KEY` cannot be recovered, so tokens signed with that key will no longer validate.
|
|
483
485
|
|
|
484
486
|
Run `python lenora.py apikey` inside a project to set `AUTHENTICATION = "api_key"`, add the `APIKey` model to `app/models.py` when it is missing, and run the migration workflow. The command is safe to repeat; it leaves an existing model in place and applies no migration when the database is already current. **The built-in API-key authenticator uses the framework `User` model.** It hashes the presented key and compares it with the digest in `User.api_key`; `register_user(..., authentication="api_key")` writes that digest and returns the raw key once. The generated `APIKey` table is a separate, optional app-managed key registry, linked to `User` by `user_id`; the default authenticator and `register_user()` do not automatically read or populate it. If your app wants that table to be the authentication lookup source, implement and configure that lookup explicitly. Never store raw keys in `key_hash`.
|
|
@@ -1580,6 +1582,8 @@ class User(BaseUser):
|
|
|
1580
1582
|
|
|
1581
1583
|
Import the extended `User` from `app.models` in application code and run `python lenora.py migration`. Do not set a second table name for this subclass; it extends the framework's existing `user` table. `bio` is nullable because MySQL does not support defaults on `TEXT` columns; if existing rows need an empty string instead of `NULL`, add a data backfill to the generated migration. Ordinary subclasses of the abstract `Model` base still get a table inferred from their class name.
|
|
1582
1584
|
|
|
1585
|
+
LenAPI preserves Boolean server defaults as Boolean literals in generated migrations so a revision created with SQLite can also apply on PostgreSQL. For an already-generated revision that contains `server_default=sa.text('0')` on a Boolean column, update it to `server_default=sa.false()` before applying it to PostgreSQL.
|
|
1586
|
+
|
|
1583
1587
|
For API-key mode, call `register_user(data=..., authentication="api_key")` from your own registration route. It generates a URL-safe key with 32 bytes of cryptographically secure randomness and returns it once as plain text. LenAPI stores only its SHA-256 digest in the nullable `user.api_key` column, so the original key cannot be recovered later. Send the returned key on authenticated requests with `X-API-Key: <key>`. The `python lenora.py apikey` command also creates an `APIKey` table for app-managed key records, but the built-in authenticator looks up `User.api_key`; the helper does not automatically add rows to that separate table.
|
|
1584
1588
|
|
|
1585
1589
|
Use `register_user()` from your own registration handler if you want the framework's user creation and password handling. The password encoding uses Django's `pbkdf2_sha256` format, so Django's password hashers can verify it; this is one-way hashing, not reversible encryption. See [Django password management](https://docs.djangoproject.com/en/6.0/topics/auth/passwords/) for the encoded format and verification helpers.
|
|
@@ -672,7 +672,11 @@ class Application(Router):
|
|
|
672
672
|
media_root=self.media_root,
|
|
673
673
|
private_media_root=self.private_media_root,
|
|
674
674
|
)
|
|
675
|
-
request.background_tasks = BackgroundTasks(
|
|
675
|
+
request.background_tasks = BackgroundTasks(
|
|
676
|
+
session_factory=self.session_factory,
|
|
677
|
+
async_session_factory=self.async_session_factory,
|
|
678
|
+
database_backend=self.database_type,
|
|
679
|
+
)
|
|
676
680
|
session = None
|
|
677
681
|
async_session = None
|
|
678
682
|
session_token = None
|
|
@@ -12,6 +12,14 @@ from collections.abc import Callable
|
|
|
12
12
|
from sqlalchemy import and_, or_, select, update
|
|
13
13
|
|
|
14
14
|
from .models import BACKGROUND_JOBS_TABLE
|
|
15
|
+
from .models import (
|
|
16
|
+
reset_current_async_session,
|
|
17
|
+
reset_current_database_backend,
|
|
18
|
+
reset_current_session,
|
|
19
|
+
set_current_async_session,
|
|
20
|
+
set_current_database_backend,
|
|
21
|
+
set_current_session,
|
|
22
|
+
)
|
|
15
23
|
|
|
16
24
|
from .logging import get_logger
|
|
17
25
|
|
|
@@ -24,8 +32,12 @@ _MEMORY_QUEUE_JOBS: dict[str, dict[str, dict]] = {}
|
|
|
24
32
|
class BackgroundTasks:
|
|
25
33
|
"""Collect functions to run after the response body has been sent."""
|
|
26
34
|
|
|
27
|
-
def __init__(self
|
|
35
|
+
def __init__(self, *, session_factory=None, async_session_factory=None,
|
|
36
|
+
database_backend: str | None = None) -> None:
|
|
28
37
|
self._tasks: list[tuple[Callable, tuple, dict]] = []
|
|
38
|
+
self._session_factory = session_factory
|
|
39
|
+
self._async_session_factory = async_session_factory
|
|
40
|
+
self._database_backend = database_backend
|
|
29
41
|
|
|
30
42
|
def add_task(self, function: Callable, *args, **kwargs) -> None:
|
|
31
43
|
if not callable(function):
|
|
@@ -37,9 +49,56 @@ class BackgroundTasks:
|
|
|
37
49
|
for function, args, kwargs in tasks:
|
|
38
50
|
try:
|
|
39
51
|
if inspect.iscoroutinefunction(function):
|
|
40
|
-
|
|
52
|
+
# Async handlers run on this event-loop thread, so create
|
|
53
|
+
# their independent sessions and bind them to this context.
|
|
54
|
+
session = self._session_factory() if self._session_factory else None
|
|
55
|
+
async_session = (
|
|
56
|
+
self._async_session_factory() if self._async_session_factory else None
|
|
57
|
+
)
|
|
58
|
+
session_token = set_current_session(session) if session is not None else None
|
|
59
|
+
async_session_token = (
|
|
60
|
+
set_current_async_session(async_session)
|
|
61
|
+
if async_session is not None else None
|
|
62
|
+
)
|
|
63
|
+
backend_token = (
|
|
64
|
+
set_current_database_backend(self._database_backend)
|
|
65
|
+
if self._database_backend is not None else None
|
|
66
|
+
)
|
|
67
|
+
try:
|
|
68
|
+
await function(*args, **kwargs)
|
|
69
|
+
finally:
|
|
70
|
+
if backend_token is not None:
|
|
71
|
+
reset_current_database_backend(backend_token)
|
|
72
|
+
if async_session_token is not None:
|
|
73
|
+
reset_current_async_session(async_session_token)
|
|
74
|
+
if session_token is not None:
|
|
75
|
+
reset_current_session(session_token)
|
|
76
|
+
if session is not None:
|
|
77
|
+
session.close()
|
|
78
|
+
if async_session is not None:
|
|
79
|
+
await async_session.close()
|
|
41
80
|
else:
|
|
42
|
-
|
|
81
|
+
def invoke_sync_task():
|
|
82
|
+
# SQLAlchemy sessions are thread-affine for several
|
|
83
|
+
# drivers (including SQLite), so construct, use, and
|
|
84
|
+
# close the task session in the same worker thread.
|
|
85
|
+
session = self._session_factory() if self._session_factory else None
|
|
86
|
+
session_token = set_current_session(session) if session is not None else None
|
|
87
|
+
backend_token = (
|
|
88
|
+
set_current_database_backend(self._database_backend)
|
|
89
|
+
if self._database_backend is not None else None
|
|
90
|
+
)
|
|
91
|
+
try:
|
|
92
|
+
return function(*args, **kwargs)
|
|
93
|
+
finally:
|
|
94
|
+
if backend_token is not None:
|
|
95
|
+
reset_current_database_backend(backend_token)
|
|
96
|
+
if session_token is not None:
|
|
97
|
+
reset_current_session(session_token)
|
|
98
|
+
if session is not None:
|
|
99
|
+
session.close()
|
|
100
|
+
|
|
101
|
+
result = await asyncio.to_thread(invoke_sync_task)
|
|
43
102
|
if inspect.isawaitable(result):
|
|
44
103
|
await result
|
|
45
104
|
except Exception:
|
|
@@ -119,6 +119,8 @@ TOKEN = {
|
|
|
119
119
|
|
|
120
120
|
from lenapi_bootstrap import create_app
|
|
121
121
|
|
|
122
|
+
# Keep app creation before imports from app.models or routers. This configures
|
|
123
|
+
# the project namespace for direct ``uvicorn main:app`` startup.
|
|
122
124
|
app = create_app(__file__, __package__)
|
|
123
125
|
|
|
124
126
|
|
|
@@ -231,6 +233,7 @@ from sqlalchemy import create_engine, inspect
|
|
|
231
233
|
|
|
232
234
|
from lenapi import Model
|
|
233
235
|
from lenapi.project import project_namespace, project_object_name
|
|
236
|
+
from lenapi.migration_render import render_migration_item
|
|
234
237
|
|
|
235
238
|
config = context.config
|
|
236
239
|
|
|
@@ -291,6 +294,7 @@ def run_migrations_offline():
|
|
|
291
294
|
dialect_opts={"paramstyle": "named"},
|
|
292
295
|
compare_type=True,
|
|
293
296
|
include_object=include_migration_object,
|
|
297
|
+
render_item=render_migration_item,
|
|
294
298
|
)
|
|
295
299
|
with context.begin_transaction():
|
|
296
300
|
context.run_migrations()
|
|
@@ -307,6 +311,7 @@ def run_migrations_online():
|
|
|
307
311
|
version_table=project_object_name("alembic_version"),
|
|
308
312
|
compare_type=True,
|
|
309
313
|
include_object=include_migration_object,
|
|
314
|
+
render_item=render_migration_item,
|
|
310
315
|
render_as_batch=connection.dialect.name == "sqlite",
|
|
311
316
|
)
|
|
312
317
|
with context.begin_transaction():
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Alembic render helpers for portable LenAPI migrations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from sqlalchemy.sql.elements import False_, True_
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def render_migration_item(type_: str, item, autogen_context):
|
|
9
|
+
"""Keep Boolean server defaults as Boolean expressions in revisions.
|
|
10
|
+
|
|
11
|
+
Alembic renders ``false()`` using the dialect used to generate a revision.
|
|
12
|
+
On SQLite that becomes ``sa.text('0')``; such a revision then fails when
|
|
13
|
+
applied to PostgreSQL. Preserve the expression so the target dialect
|
|
14
|
+
compiles it to its native Boolean literal at migration time.
|
|
15
|
+
"""
|
|
16
|
+
if type_ != "server_default":
|
|
17
|
+
return False
|
|
18
|
+
|
|
19
|
+
expression = getattr(item, "arg", item)
|
|
20
|
+
sqlalchemy_prefix = autogen_context.opts.get("sqlalchemy_module_prefix", "sa.")
|
|
21
|
+
if isinstance(expression, False_):
|
|
22
|
+
return f"{sqlalchemy_prefix}false()"
|
|
23
|
+
if isinstance(expression, True_):
|
|
24
|
+
return f"{sqlalchemy_prefix}true()"
|
|
25
|
+
return False
|
|
@@ -9,9 +9,10 @@ import re
|
|
|
9
9
|
import uuid
|
|
10
10
|
from urllib.parse import urlsplit
|
|
11
11
|
|
|
12
|
-
from sqlalchemy import BigInteger, Boolean, CheckConstraint, Column, Date, DateTime, Float, ForeignKey, Integer, Interval, JSON, MetaData, Numeric, String, Table, Text, Time, Uuid, UniqueConstraint, and_, delete, false, func, inspect, or_, select
|
|
12
|
+
from sqlalchemy import BigInteger, Boolean, CheckConstraint, Column, Date, DateTime, Float, ForeignKey, Integer, Interval, JSON, MetaData, Numeric, String, Table, Text, Time, Uuid, UniqueConstraint, and_, delete, false, func, inspect, or_, select, text
|
|
13
13
|
from sqlalchemy.exc import IntegrityError
|
|
14
14
|
from sqlalchemy.orm import DeclarativeBase, Mapped, MappedColumn, Mapper, backref, declared_attr, mapped_column, object_session, relationship, selectinload
|
|
15
|
+
from sqlalchemy.sql.elements import False_, True_
|
|
15
16
|
from sqlalchemy import event
|
|
16
17
|
|
|
17
18
|
from .response import HTTPException
|
|
@@ -1615,8 +1616,19 @@ TExtfield = TextField
|
|
|
1615
1616
|
|
|
1616
1617
|
|
|
1617
1618
|
def BooleanField(**kwargs):
|
|
1618
|
-
"""Declare a boolean column that defaults to ``True`` unless overridden.
|
|
1619
|
+
"""Declare a boolean column that defaults to ``True`` unless overridden.
|
|
1620
|
+
|
|
1621
|
+
Normalize SQLAlchemy's dialect-compiled Boolean server defaults to stable
|
|
1622
|
+
SQL literals. Alembic otherwise renders ``false()`` as ``0`` when a
|
|
1623
|
+
revision is generated against SQLite, which PostgreSQL rejects later.
|
|
1624
|
+
"""
|
|
1619
1625
|
kwargs.setdefault("default", True)
|
|
1626
|
+
server_default = kwargs.get("server_default")
|
|
1627
|
+
expression = getattr(server_default, "arg", server_default)
|
|
1628
|
+
if isinstance(expression, False_):
|
|
1629
|
+
kwargs["server_default"] = text("false")
|
|
1630
|
+
elif isinstance(expression, True_):
|
|
1631
|
+
kwargs["server_default"] = text("true")
|
|
1620
1632
|
return _field(Boolean, **kwargs)
|
|
1621
1633
|
|
|
1622
1634
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: lenapi
|
|
3
|
-
Version: 0.1.4.
|
|
3
|
+
Version: 0.1.4.5
|
|
4
4
|
Summary: A modern ASGI framework with Pydantic validation, sync and async database access, WebSockets, authentication, and integrated API documentation.
|
|
5
5
|
Author: Maekandex Communication Limitation
|
|
6
6
|
Author-email: "Ifeanyi M. Onovo" <ifeanyi@maekandex.com.ng>
|
|
@@ -531,6 +531,8 @@ python lenora.py run
|
|
|
531
531
|
|
|
532
532
|
Use the installed `lenora` command to create the first project; `python lenora.py ...` commands are available after entering the generated project. The server listens on `127.0.0.1:8009` by default. The generated application contains `app/models.py`, `app/schemas.py`, `settings.py`, `main.py`, a `tests/` package, a project-local CLI launcher, `alembic.ini`, and a `migrations/` folder. The default `User` model and authentication implementation live in the framework. The initial migration includes the framework's `User` table automatically. `LENAPI()` sets up `app.authenticator` from `settings.AUTHENTICATION`, but route protection is opt-in: pass an authenticator to `LENAPI(auth=...)`, `Router(auth=...)`, or a route's `auth=` parameter. This keeps login and registration routes public unless you protect them too. The framework repository contains the installable `lenapi` package; create an application scaffold separately with `lenora startproject`.
|
|
533
533
|
|
|
534
|
+
Generated `main.py` creates the configured application before importing project models or routers. This order sets `PROJECT_NAMESPACE` before SQLAlchemy declares model tables and lets you run the generated app directly with Uvicorn, for example `uvicorn main:app --host 0.0.0.0 --port 8010`. Keep `create_app(__file__, __package__)` above imports that load `app.models`; otherwise Uvicorn may load unprefixed table names that do not match the namespaced tables created by migrations.
|
|
535
|
+
|
|
534
536
|
If `settings.py` is accidentally deleted, run `python lenora.py repair-settings` from the project directory. It recreates the generated defaults only when the file is missing and refuses to overwrite an existing settings file. The recreated file gets fresh `SECRET_KEY` and `API_KEY` values; review it before starting the app. The old `SECRET_KEY` cannot be recovered, so tokens signed with that key will no longer validate.
|
|
535
537
|
|
|
536
538
|
Run `python lenora.py apikey` inside a project to set `AUTHENTICATION = "api_key"`, add the `APIKey` model to `app/models.py` when it is missing, and run the migration workflow. The command is safe to repeat; it leaves an existing model in place and applies no migration when the database is already current. **The built-in API-key authenticator uses the framework `User` model.** It hashes the presented key and compares it with the digest in `User.api_key`; `register_user(..., authentication="api_key")` writes that digest and returns the raw key once. The generated `APIKey` table is a separate, optional app-managed key registry, linked to `User` by `user_id`; the default authenticator and `register_user()` do not automatically read or populate it. If your app wants that table to be the authentication lookup source, implement and configure that lookup explicitly. Never store raw keys in `key_hash`.
|
|
@@ -1632,6 +1634,8 @@ class User(BaseUser):
|
|
|
1632
1634
|
|
|
1633
1635
|
Import the extended `User` from `app.models` in application code and run `python lenora.py migration`. Do not set a second table name for this subclass; it extends the framework's existing `user` table. `bio` is nullable because MySQL does not support defaults on `TEXT` columns; if existing rows need an empty string instead of `NULL`, add a data backfill to the generated migration. Ordinary subclasses of the abstract `Model` base still get a table inferred from their class name.
|
|
1634
1636
|
|
|
1637
|
+
LenAPI preserves Boolean server defaults as Boolean literals in generated migrations so a revision created with SQLite can also apply on PostgreSQL. For an already-generated revision that contains `server_default=sa.text('0')` on a Boolean column, update it to `server_default=sa.false()` before applying it to PostgreSQL.
|
|
1638
|
+
|
|
1635
1639
|
For API-key mode, call `register_user(data=..., authentication="api_key")` from your own registration route. It generates a URL-safe key with 32 bytes of cryptographically secure randomness and returns it once as plain text. LenAPI stores only its SHA-256 digest in the nullable `user.api_key` column, so the original key cannot be recovered later. Send the returned key on authenticated requests with `X-API-Key: <key>`. The `python lenora.py apikey` command also creates an `APIKey` table for app-managed key records, but the built-in authenticator looks up `User.api_key`; the helper does not automatically add rows to that separate table.
|
|
1636
1640
|
|
|
1637
1641
|
Use `register_user()` from your own registration handler if you want the framework's user creation and password handling. The password encoding uses Django's `pbkdf2_sha256` format, so Django's password hashers can verify it; this is one-way hashing, not reversible encryption. See [Django password management](https://docs.djangoproject.com/en/6.0/topics/auth/passwords/) for the encoded format and verification helpers.
|
|
@@ -16,6 +16,7 @@ lenapi/dependencies.py
|
|
|
16
16
|
lenapi/docs_guard.py
|
|
17
17
|
lenapi/logging.py
|
|
18
18
|
lenapi/middleware.py
|
|
19
|
+
lenapi/migration_render.py
|
|
19
20
|
lenapi/model.py
|
|
20
21
|
lenapi/models.py
|
|
21
22
|
lenapi/mongodb.py
|
|
@@ -41,6 +42,7 @@ tests/test_cli_settings_recovery.py
|
|
|
41
42
|
tests/test_docs_guard.py
|
|
42
43
|
tests/test_framework_features.py
|
|
43
44
|
tests/test_media_upload.py
|
|
45
|
+
tests/test_migration_render.py
|
|
44
46
|
tests/test_mongodb.py
|
|
45
47
|
tests/test_platform_services.py
|
|
46
48
|
tests/test_project_isolation.py
|
|
@@ -54,7 +54,12 @@ def configure_project(source_file: str, package: str | None = None):
|
|
|
54
54
|
|
|
55
55
|
|
|
56
56
|
def create_app(source_file: str, package: str | None = None):
|
|
57
|
-
"""Create a configured app and import
|
|
57
|
+
"""Create a configured app and import project models under its namespace.
|
|
58
|
+
|
|
59
|
+
Call this before importing application routers or models. Generated
|
|
60
|
+
``main.py`` does so at module import time, which lets Uvicorn load
|
|
61
|
+
``main:app`` directly without the ``lenora`` launcher.
|
|
62
|
+
"""
|
|
58
63
|
settings = configure_project(source_file, package)
|
|
59
64
|
model_module = f"{package}.app.models" if package else "app.models"
|
|
60
65
|
importlib.import_module(model_module)
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "lenapi"
|
|
7
|
-
version = "0.1.4.
|
|
7
|
+
version = "0.1.4.5"
|
|
8
8
|
description = "A modern ASGI framework with Pydantic validation, sync and async database access, WebSockets, authentication, and integrated API documentation."
|
|
9
9
|
authors = [
|
|
10
10
|
{name = "Ifeanyi M. Onovo", email = "ifeanyi@maekandex.com.ng"},
|
|
@@ -228,6 +228,32 @@ def test_typed_path_query_body_request_and_background_tasks():
|
|
|
228
228
|
app.database.close()
|
|
229
229
|
|
|
230
230
|
|
|
231
|
+
def test_sync_background_task_gets_fresh_database_session(tmp_path):
|
|
232
|
+
app = Application(
|
|
233
|
+
database=Database(f"sqlite:///{tmp_path / 'background.sqlite3'}"),
|
|
234
|
+
security_storage="memory",
|
|
235
|
+
)
|
|
236
|
+
Model.metadata.create_all(app.database.engine, tables=[FeatureRecord.__table__])
|
|
237
|
+
|
|
238
|
+
@app.post("/audit")
|
|
239
|
+
def audit(request: Request):
|
|
240
|
+
request.background_tasks.add_task(FeatureRecord.create, name="background-audit")
|
|
241
|
+
return {"accepted": True}
|
|
242
|
+
|
|
243
|
+
status, _headers, result = json_request(app, "/audit", method="POST")
|
|
244
|
+
assert status == 200
|
|
245
|
+
assert result == {"accepted": True}
|
|
246
|
+
|
|
247
|
+
with app.database.engine.connect() as connection:
|
|
248
|
+
rows = connection.execute(
|
|
249
|
+
select(FeatureRecord.__table__).where(
|
|
250
|
+
FeatureRecord.__table__.c.name == "background-audit"
|
|
251
|
+
)
|
|
252
|
+
).mappings().all()
|
|
253
|
+
assert len(rows) == 1
|
|
254
|
+
app.database.close()
|
|
255
|
+
|
|
256
|
+
|
|
231
257
|
def test_dependency_results_are_cached_and_cycles_return_422():
|
|
232
258
|
app = make_app()
|
|
233
259
|
calls = []
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Regression tests for portable generated database defaults."""
|
|
2
|
+
|
|
3
|
+
from types import SimpleNamespace
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from sqlalchemy import Boolean, Column, MetaData, Table, false, true
|
|
7
|
+
from sqlalchemy.dialects import mysql, postgresql, sqlite
|
|
8
|
+
from sqlalchemy.schema import CreateTable, DefaultClause
|
|
9
|
+
|
|
10
|
+
from lenapi.migration_render import render_migration_item
|
|
11
|
+
from lenapi.models import BooleanField
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@pytest.mark.parametrize(
|
|
15
|
+
("expression", "expected_sql", "expected_render"),
|
|
16
|
+
[
|
|
17
|
+
(false(), "false", "sa.false()"),
|
|
18
|
+
(true(), "true", "sa.true()"),
|
|
19
|
+
],
|
|
20
|
+
)
|
|
21
|
+
def test_boolean_field_server_defaults_are_portable(
|
|
22
|
+
expression, expected_sql, expected_render
|
|
23
|
+
):
|
|
24
|
+
field = BooleanField(default=False, nullable=False, server_default=expression)
|
|
25
|
+
default = field.column.server_default
|
|
26
|
+
|
|
27
|
+
assert str(default.arg) == expected_sql
|
|
28
|
+
for dialect in (sqlite.dialect(), postgresql.dialect(), mysql.dialect()):
|
|
29
|
+
table = Table(
|
|
30
|
+
f"boolean_default_{dialect.name}",
|
|
31
|
+
MetaData(),
|
|
32
|
+
Column("enabled", Boolean, server_default=default.arg, nullable=False),
|
|
33
|
+
)
|
|
34
|
+
ddl = str(CreateTable(table).compile(dialect=dialect))
|
|
35
|
+
assert f"default {expected_sql}" in ddl.lower()
|
|
36
|
+
|
|
37
|
+
rendered = render_migration_item(
|
|
38
|
+
"server_default",
|
|
39
|
+
DefaultClause(expression),
|
|
40
|
+
SimpleNamespace(opts={"sqlalchemy_module_prefix": "sa."}),
|
|
41
|
+
)
|
|
42
|
+
assert rendered == expected_render
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_non_boolean_server_default_uses_alembic_default_renderer():
|
|
46
|
+
assert render_migration_item(
|
|
47
|
+
"server_default", "CURRENT_TIMESTAMP", SimpleNamespace(opts={})
|
|
48
|
+
) is False
|
|
@@ -171,6 +171,50 @@ def test_generated_project_uses_namespaced_tables_and_requires_orphan_confirmati
|
|
|
171
171
|
).fetchone() is None
|
|
172
172
|
|
|
173
173
|
|
|
174
|
+
def test_generated_project_imports_with_uvicorn_before_model_declarations(tmp_path):
|
|
175
|
+
env = os.environ.copy()
|
|
176
|
+
env.pop("LENAPI_PROJECT_NAME", None)
|
|
177
|
+
env.pop("LENAPI_PROJECT_NAMESPACE", None)
|
|
178
|
+
env["PYTHONPATH"] = str(ROOT) + os.pathsep + env.get("PYTHONPATH", "")
|
|
179
|
+
created = subprocess.run(
|
|
180
|
+
[sys.executable, "-c", "from lenapi.cli import main; main()", "startproject", "demo"],
|
|
181
|
+
cwd=tmp_path,
|
|
182
|
+
env=env,
|
|
183
|
+
capture_output=True,
|
|
184
|
+
text=True,
|
|
185
|
+
check=False,
|
|
186
|
+
)
|
|
187
|
+
assert created.returncode == 0, created.stdout + created.stderr
|
|
188
|
+
|
|
189
|
+
project_dir = tmp_path / "demo"
|
|
190
|
+
models_path = project_dir / "app" / "models.py"
|
|
191
|
+
with models_path.open("a", encoding="utf-8") as models_file:
|
|
192
|
+
models_file.write(
|
|
193
|
+
"\nfrom lenapi import model\n"
|
|
194
|
+
"class UvicornNamespaceProbe(model.Model):\n"
|
|
195
|
+
" value = model.StringField(max_length=20)\n"
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
direct_import = subprocess.run(
|
|
199
|
+
[
|
|
200
|
+
sys.executable,
|
|
201
|
+
"-c",
|
|
202
|
+
"from uvicorn.importer import import_from_string\n"
|
|
203
|
+
"app = import_from_string('main:app')\n"
|
|
204
|
+
"from app.models import UvicornNamespaceProbe\n"
|
|
205
|
+
"assert UvicornNamespaceProbe.__table__.name == "
|
|
206
|
+
"f'{app.project_namespace}_uvicornnamespaceprobe'\n"
|
|
207
|
+
"assert app.project_name == 'demo'\n",
|
|
208
|
+
],
|
|
209
|
+
cwd=project_dir,
|
|
210
|
+
env=env,
|
|
211
|
+
capture_output=True,
|
|
212
|
+
text=True,
|
|
213
|
+
check=False,
|
|
214
|
+
)
|
|
215
|
+
assert direct_import.returncode == 0, direct_import.stdout + direct_import.stderr
|
|
216
|
+
|
|
217
|
+
|
|
174
218
|
def test_project_settings_identity_matches_project_directory(tmp_path, monkeypatch):
|
|
175
219
|
monkeypatch.delenv("LENAPI_PROJECT_NAME", raising=False)
|
|
176
220
|
monkeypatch.delenv("LENAPI_PROJECT_NAMESPACE", raising=False)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|