lenapi 0.1.4.8__tar.gz → 0.1.4.9__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.8 → lenapi-0.1.4.9}/PKG-INFO +135 -2
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/README.md +130 -1
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/__init__.py +12 -2
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/application.py +14 -2
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/cli.py +193 -11
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/database.py +101 -4
- lenapi-0.1.4.9/lenapi/graphql.py +137 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/models.py +132 -17
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/mongodb.py +37 -2
- lenapi-0.1.4.9/lenapi/signals.py +111 -0
- lenapi-0.1.4.9/lenapi/soap.py +247 -0
- lenapi-0.1.4.9/lenapi/transaction.py +165 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi.egg-info/PKG-INFO +135 -2
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi.egg-info/SOURCES.txt +5 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi.egg-info/entry_points.txt +1 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi.egg-info/requires.txt +6 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/pyproject.toml +4 -1
- lenapi-0.1.4.9/tests/test_optional_protocols.py +81 -0
- lenapi-0.1.4.9/tests/test_signals_and_deployment.py +221 -0
- lenapi-0.1.4.8/lenapi/transaction.py +0 -76
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/LICENSE +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/admin.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/auth.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/authentication.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/authorization.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/background.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/concurrency.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/dependencies.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/docs_guard.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/logging.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/middleware.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/migration_render.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/model.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/openapi.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/parameters.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/project.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/request.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/response.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/security.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/security_store.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/sentinels.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/service.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi/throttling.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi.egg-info/dependency_links.txt +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi.egg-info/top_level.txt +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/lenapi_bootstrap.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/setup.cfg +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/tests/test_admin_console.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/tests/test_cli_settings_recovery.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/tests/test_docs_guard.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/tests/test_framework_features.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/tests/test_media_upload.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/tests/test_migration_render.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/tests/test_mongodb.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/tests/test_platform_services.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/tests/test_project_isolation.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/tests/test_security_patch.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/tests/test_sentinels.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/tests/test_throttle.py +0 -0
- {lenapi-0.1.4.8 → lenapi-0.1.4.9}/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.9
|
|
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>
|
|
@@ -48,6 +48,10 @@ Provides-Extra: mongodb
|
|
|
48
48
|
Requires-Dist: pymongo<5,>=4.13; extra == "mongodb"
|
|
49
49
|
Provides-Extra: monitoring
|
|
50
50
|
Requires-Dist: psutil<8,>=5.9; extra == "monitoring"
|
|
51
|
+
Provides-Extra: graphql
|
|
52
|
+
Requires-Dist: graphql-core<4,>=3.2; extra == "graphql"
|
|
53
|
+
Provides-Extra: soap
|
|
54
|
+
Requires-Dist: defusedxml<1,>=0.7.1; extra == "soap"
|
|
51
55
|
Dynamic: license-file
|
|
52
56
|
|
|
53
57
|
# lenApi
|
|
@@ -69,6 +73,7 @@ LenAPI aims to reduce repetitive code and simplify common integrations, helping
|
|
|
69
73
|
- Validated public and private file uploads, middleware, throttling, and optional gzip compression.
|
|
70
74
|
- An optional model admin console with explicit model/field allow-lists, per-model permissions, and CPU/RAM/process monitoring.
|
|
71
75
|
- Independent generated projects that can run separately or be mounted under a path in a primary project.
|
|
76
|
+
- Optional GraphQL and SOAP integrations, installed separately so REST-only projects keep the core lightweight.
|
|
72
77
|
|
|
73
78
|
See the [LenAPI documentation](https://lenapi.site/) for setup guides and runnable examples.
|
|
74
79
|
|
|
@@ -119,6 +124,81 @@ auth_logger.warning("Login attempt rejected")
|
|
|
119
124
|
|
|
120
125
|
LenApi prints `INFO` and higher by default. You can change the level or add your own handlers with Python's standard `logging` module.
|
|
121
126
|
|
|
127
|
+
## Optional GraphQL and SOAP
|
|
128
|
+
|
|
129
|
+
GraphQL and SOAP are optional integrations. Install only the protocol you use:
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
python -m pip install 'lenapi[graphql]'
|
|
133
|
+
python -m pip install 'lenapi[soap]'
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### GraphQL
|
|
137
|
+
|
|
138
|
+
The GraphQL integration uses `graphql-core`. Define the schema with the
|
|
139
|
+
re-exports in `lenapi.graphql`, then mount its router on a LenAPI app. The
|
|
140
|
+
endpoint accepts JSON POST requests and query-only GET requests; mutations
|
|
141
|
+
must use POST. By default, the current LenAPI `Request` is passed as the
|
|
142
|
+
resolver context.
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
from lenapi import LENAPI, graphql
|
|
146
|
+
|
|
147
|
+
app = LENAPI()
|
|
148
|
+
|
|
149
|
+
def resolve_greeting(_root, info, name="world"):
|
|
150
|
+
return f"Hello, {name}!"
|
|
151
|
+
|
|
152
|
+
query = graphql.GraphQLObjectType(
|
|
153
|
+
"Query",
|
|
154
|
+
{
|
|
155
|
+
"greeting": graphql.GraphQLField(
|
|
156
|
+
graphql.GraphQLString,
|
|
157
|
+
args={"name": graphql.GraphQLArgument(graphql.GraphQLString)},
|
|
158
|
+
resolve=resolve_greeting,
|
|
159
|
+
)
|
|
160
|
+
},
|
|
161
|
+
)
|
|
162
|
+
schema = graphql.GraphQLSchema(query=query)
|
|
163
|
+
graphql_api = graphql.GraphQLRouter(schema, path="/graphql")
|
|
164
|
+
app.include_router(graphql_api.router)
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
POST `{"query":"{ greeting }"}` to `/graphql`. Use `context_value=` on
|
|
168
|
+
`GraphQLRouter` to provide a custom
|
|
169
|
+
sync/async resolver context, for example the authenticated user and request.
|
|
170
|
+
Authentication can also be attached to the LenAPI router when mounting it.
|
|
171
|
+
|
|
172
|
+
### SOAP 1.1
|
|
173
|
+
|
|
174
|
+
The SOAP integration uses `defusedxml` to parse SOAP envelopes safely. Register
|
|
175
|
+
operations with `SOAPService`, then include its router. `GET /soap?wsdl`
|
|
176
|
+
returns a WSDL document generated from operation names and scalar annotations.
|
|
177
|
+
This initial service supports SOAP 1.1 document/literal calls with scalar
|
|
178
|
+
`str`, `int`, `float`, and `bool` arguments; use REST or GraphQL for richer
|
|
179
|
+
schemas and more complex API interactions.
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
from lenapi import LENAPI, soap
|
|
183
|
+
|
|
184
|
+
app = LENAPI()
|
|
185
|
+
service = soap.SOAPService(
|
|
186
|
+
"Calculator",
|
|
187
|
+
target_namespace="https://example.com/calculator",
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
@service.operation
|
|
191
|
+
def add(left: int, right: int) -> int:
|
|
192
|
+
return left + right
|
|
193
|
+
|
|
194
|
+
app.include_router(service.router(path="/soap"))
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
SOAP clients can retrieve the service description at `/soap?wsdl` and send
|
|
198
|
+
SOAP 1.1 XML envelopes to `/soap`. Sync and async operation functions are
|
|
199
|
+
supported. Keep authorization and business validation inside operation
|
|
200
|
+
functions or protect the LenAPI router according to your application policy.
|
|
201
|
+
|
|
122
202
|
## WebSockets
|
|
123
203
|
|
|
124
204
|
WebSockets keep one connection open so a client and server can send messages in
|
|
@@ -1821,10 +1901,21 @@ DATABASE_URL = f"sqlite:///{BASE_DIR / 'lenapi.db'}"
|
|
|
1821
1901
|
# MONGODB_DATABASE = "app_db"
|
|
1822
1902
|
|
|
1823
1903
|
ACTIVATE_ASYNC = False
|
|
1904
|
+
|
|
1905
|
+
# SQLAlchemy connection pool settings (SQLite, MySQL, and PostgreSQL only).
|
|
1906
|
+
# 0 closes physical connections when each request/session returns them to the pool.
|
|
1907
|
+
DATABASE_CONN_MAX_AGE = 0
|
|
1908
|
+
DATABASE_POOL_SIZE = 5
|
|
1909
|
+
DATABASE_MAX_OVERFLOW = 0
|
|
1910
|
+
DATABASE_POOL_TIMEOUT = 30
|
|
1824
1911
|
```
|
|
1825
1912
|
|
|
1826
1913
|
LenAPI chooses the supported synchronous driver for a selected MySQL or PostgreSQL URL. Async access uses `aiosqlite` for SQLite; install `lenapi[async-mysql]` for MySQL or `lenapi[async-postgres]` for PostgreSQL. MongoDB uses its separate sync/async document API.
|
|
1827
1914
|
|
|
1915
|
+
`DATABASE_CONN_MAX_AGE` applies independently to the synchronous and asynchronous SQL connection pools. The default `0` closes a physical connection when the request or database session returns it to the pool; the next database use opens a fresh connection. A positive value, such as `300`, allows connections to be reused and recycles a connection once it reaches that age when it is checked out. It is an age limit, not an exact idle-time timer. In-memory SQLite keeps its connection and uses its dialect-selected pool so its database contents are not lost; the pool size settings are not applied to that special case. These options do not configure MongoDB connections.
|
|
1916
|
+
|
|
1917
|
+
`DATABASE_POOL_SIZE` limits the number of retained connections per engine, while `DATABASE_MAX_OVERFLOW` allows a temporary number of additional concurrent connections. `DATABASE_POOL_TIMEOUT` is how many seconds a checkout waits for a connection before raising a pool timeout. Sync and async engines have separate pools, so account for both when setting database server connection limits. For example, a pool size of 5 with overflow 0 permits up to 5 concurrent connections for each engine in one application worker.
|
|
1918
|
+
|
|
1828
1919
|
### MongoDB documents
|
|
1829
1920
|
|
|
1830
1921
|
Install the official PyMongo driver extra with `python -m pip install -e '.[mongodb]'`. Create a `MongoDatabase` using a MongoDB URI and database name, then bind Pydantic document classes to it. The default collection name is the lower-case document class name; set `collection_name` to override it. MongoDB creates collections on first write; `migration` can also pre-create empty collections for imported `MongoDocument` classes. Document field changes do not use Alembic schema revisions.
|
|
@@ -2024,6 +2115,14 @@ class Enrollment(model.Model):
|
|
|
2024
2115
|
|
|
2025
2116
|
Run the commands from the generated project root. Import application models before migration discovery, normally by importing them in `main.py`.
|
|
2026
2117
|
|
|
2118
|
+
Before deployment, run the configuration check from the project root:
|
|
2119
|
+
|
|
2120
|
+
```bash
|
|
2121
|
+
python lenora.py check --deploy
|
|
2122
|
+
```
|
|
2123
|
+
|
|
2124
|
+
It checks the production-sensitive settings and database URL scheme without printing credential values. It fails for unsafe settings such as `DEBUG=True`, a missing or weak secret, in-memory security storage, or a database type/URL mismatch. A warning about an in-memory cache means that cache entries are local to each process; use a shared backend when the app runs on multiple workers. The command validates configuration, but it does not prove that a remote database or Redis service is reachable.
|
|
2125
|
+
|
|
2027
2126
|
`migration` detects schema changes against imported model metadata, creates a new Alembic revision if needed, and applies pending revisions. It does not upgrade the database when there is no new revision. Use it during development after changing relational models:
|
|
2028
2127
|
|
|
2029
2128
|
```bash
|
|
@@ -2031,6 +2130,14 @@ python lenora.py migration
|
|
|
2031
2130
|
python lenora.py migration --message "add student phone"
|
|
2032
2131
|
```
|
|
2033
2132
|
|
|
2133
|
+
To review the schema diff without creating a revision, applying a migration, or dropping namespaced orphan tables, use:
|
|
2134
|
+
|
|
2135
|
+
```bash
|
|
2136
|
+
python lenora.py migration --dry-run
|
|
2137
|
+
```
|
|
2138
|
+
|
|
2139
|
+
The preview includes project-owned orphan tables/views and reports them as requiring confirmation. A normal `migration` still asks before dropping those objects. For MongoDB, the preview lists expected collections that are missing and project-owned orphan collections, without creating or dropping anything.
|
|
2140
|
+
|
|
2034
2141
|
An existing unversioned SQLite database is adopted only when its schema matches the migration history; adoption preserves its data.
|
|
2035
2142
|
|
|
2036
2143
|
`PositiveIntegerField` and `PositiveBigIntegerField` include a named database `CHECK` constraint. LenAPI prevents Alembic's metadata-copy step from adding that constraint twice, which MySQL rejects as a duplicate constraint name. If a local revision generated by an older LenAPI contains duplicate identical `sa.CheckConstraint(...)` entries, correct or regenerate that unapplied revision before using it. MySQL uses non-transactional DDL, so a failed migration may leave some project tables created even though no revision was recorded. Check `showmigrations` and inspect the project-namespaced tables before retrying. For a disposable database, `delete_migrations` can reset this project's tables and revisions after its confirmation prompt; if the data must be preserved, reconcile the partial schema instead of deleting it.
|
|
@@ -2065,7 +2172,7 @@ python lenora.py repair-migrations
|
|
|
2065
2172
|
python lenora.py delete_migrations
|
|
2066
2173
|
```
|
|
2067
2174
|
|
|
2068
|
-
For MongoDB, `migration` and `migrate` initialize missing framework and imported document collections; they do not create Alembic revisions or migrate document fields. `showmigrations` reports that MongoDB has no Alembic revisions; `repair-migrations` and `clear_migrations` are SQL-only; `delete_migrations` drops all collections after confirmation.
|
|
2175
|
+
For MongoDB, `migration` and `migrate` initialize missing framework and imported document collections; they do not create Alembic revisions or migrate document fields. `migration --dry-run` lists collections that would be created and project-owned orphan collections that would need confirmation before removal. `showmigrations` reports that MongoDB has no Alembic revisions; `repair-migrations` and `clear_migrations` are SQL-only; `delete_migrations` drops all collections after confirmation.
|
|
2069
2176
|
|
|
2070
2177
|
Inside a request, models provide these query helpers:
|
|
2071
2178
|
|
|
@@ -2157,6 +2264,32 @@ has_python_students_async = await Student.afilter(course="Python").exists()
|
|
|
2157
2264
|
|
|
2158
2265
|
`Student.get(...)` builds a single-row lookup; call `.get()` for the model instance or `.exists()` for a boolean. The async single-row counterpart is `await Student.aget(...)`, and its existence check is `await Student.aget(...).exists()`. Multiple matches are an error rather than an arbitrary row selection. `Student.get("field", ...).get(...)` selects one or more columns; one selected column returns a scalar and multiple columns return a mapping. This is a query projection, not a uniqueness constraint. To make the database reject duplicates, declare `unique=True` on the field.
|
|
2159
2266
|
|
|
2267
|
+
### Model signals and commit callbacks
|
|
2268
|
+
|
|
2269
|
+
Connect lifecycle receivers to any `model.Model` subclass or `MongoDocument`. The sender filter is the model class; omit it to receive that signal for all models. Receivers may be synchronous or asynchronous. Async CRUD awaits async receivers automatically.
|
|
2270
|
+
|
|
2271
|
+
```python
|
|
2272
|
+
from lenapi import signals, transaction
|
|
2273
|
+
from app.models import AcademyUser, CreditLedger
|
|
2274
|
+
|
|
2275
|
+
@signals.post_save.connect(sender=AcademyUser)
|
|
2276
|
+
def grant_signup_credits(sender, instance, created, **kwargs):
|
|
2277
|
+
if created:
|
|
2278
|
+
CreditLedger.create(
|
|
2279
|
+
user_id=instance.id,
|
|
2280
|
+
amount=100,
|
|
2281
|
+
reason="signup_bonus",
|
|
2282
|
+
)
|
|
2283
|
+
|
|
2284
|
+
with transaction.atomic(app.database):
|
|
2285
|
+
user = AcademyUser.create(email="ada@example.com")
|
|
2286
|
+
transaction.on_commit(send_welcome_email, user.email)
|
|
2287
|
+
```
|
|
2288
|
+
|
|
2289
|
+
LenAPI provides `pre_save`, `post_save`, `pre_delete`, and `post_delete`. Save receivers receive `instance`, `created`, `using`, and `update_fields`; delete receivers receive `instance` and `using`. Extra values are available through `**kwargs`. A `post_save` receiver inside `transaction.atomic(...)` runs after the row is flushed but before the outer commit, so database writes made by that receiver share the transaction. Use `transaction.on_commit(callback, *args, **kwargs)` for effects that should wait for a successful commit, such as scheduling an email. A rollback discards callbacks registered in that block; callbacks from nested atomic blocks wait for the outer commit. Outside an atomic block, `on_commit` runs immediately.
|
|
2290
|
+
|
|
2291
|
+
Async receivers work with async CRUD, and async `on_commit` callbacks are awaited after `async with transaction.atomic(app.async_database)` commits. Use synchronous receivers and callbacks with synchronous atomic blocks. Receiver exceptions propagate; inside an atomic block they roll back the transaction. Instance and queryset row deletes emit delete signals. `Model.all().delete()` drops the table and does not emit row signals.
|
|
2292
|
+
|
|
2160
2293
|
### Fetch related records
|
|
2161
2294
|
|
|
2162
2295
|
With a `ForeignKeyField` such as `Student.classroom_id`, sync code can resolve the target row using `.special("classroom_id")`. It returns a proxy where that same attribute contains the related `Classroom` instance (or `None` if the foreign key is null):
|
|
@@ -17,6 +17,7 @@ LenAPI aims to reduce repetitive code and simplify common integrations, helping
|
|
|
17
17
|
- Validated public and private file uploads, middleware, throttling, and optional gzip compression.
|
|
18
18
|
- An optional model admin console with explicit model/field allow-lists, per-model permissions, and CPU/RAM/process monitoring.
|
|
19
19
|
- Independent generated projects that can run separately or be mounted under a path in a primary project.
|
|
20
|
+
- Optional GraphQL and SOAP integrations, installed separately so REST-only projects keep the core lightweight.
|
|
20
21
|
|
|
21
22
|
See the [LenAPI documentation](https://lenapi.site/) for setup guides and runnable examples.
|
|
22
23
|
|
|
@@ -67,6 +68,81 @@ auth_logger.warning("Login attempt rejected")
|
|
|
67
68
|
|
|
68
69
|
LenApi prints `INFO` and higher by default. You can change the level or add your own handlers with Python's standard `logging` module.
|
|
69
70
|
|
|
71
|
+
## Optional GraphQL and SOAP
|
|
72
|
+
|
|
73
|
+
GraphQL and SOAP are optional integrations. Install only the protocol you use:
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
python -m pip install 'lenapi[graphql]'
|
|
77
|
+
python -m pip install 'lenapi[soap]'
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### GraphQL
|
|
81
|
+
|
|
82
|
+
The GraphQL integration uses `graphql-core`. Define the schema with the
|
|
83
|
+
re-exports in `lenapi.graphql`, then mount its router on a LenAPI app. The
|
|
84
|
+
endpoint accepts JSON POST requests and query-only GET requests; mutations
|
|
85
|
+
must use POST. By default, the current LenAPI `Request` is passed as the
|
|
86
|
+
resolver context.
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from lenapi import LENAPI, graphql
|
|
90
|
+
|
|
91
|
+
app = LENAPI()
|
|
92
|
+
|
|
93
|
+
def resolve_greeting(_root, info, name="world"):
|
|
94
|
+
return f"Hello, {name}!"
|
|
95
|
+
|
|
96
|
+
query = graphql.GraphQLObjectType(
|
|
97
|
+
"Query",
|
|
98
|
+
{
|
|
99
|
+
"greeting": graphql.GraphQLField(
|
|
100
|
+
graphql.GraphQLString,
|
|
101
|
+
args={"name": graphql.GraphQLArgument(graphql.GraphQLString)},
|
|
102
|
+
resolve=resolve_greeting,
|
|
103
|
+
)
|
|
104
|
+
},
|
|
105
|
+
)
|
|
106
|
+
schema = graphql.GraphQLSchema(query=query)
|
|
107
|
+
graphql_api = graphql.GraphQLRouter(schema, path="/graphql")
|
|
108
|
+
app.include_router(graphql_api.router)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
POST `{"query":"{ greeting }"}` to `/graphql`. Use `context_value=` on
|
|
112
|
+
`GraphQLRouter` to provide a custom
|
|
113
|
+
sync/async resolver context, for example the authenticated user and request.
|
|
114
|
+
Authentication can also be attached to the LenAPI router when mounting it.
|
|
115
|
+
|
|
116
|
+
### SOAP 1.1
|
|
117
|
+
|
|
118
|
+
The SOAP integration uses `defusedxml` to parse SOAP envelopes safely. Register
|
|
119
|
+
operations with `SOAPService`, then include its router. `GET /soap?wsdl`
|
|
120
|
+
returns a WSDL document generated from operation names and scalar annotations.
|
|
121
|
+
This initial service supports SOAP 1.1 document/literal calls with scalar
|
|
122
|
+
`str`, `int`, `float`, and `bool` arguments; use REST or GraphQL for richer
|
|
123
|
+
schemas and more complex API interactions.
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
from lenapi import LENAPI, soap
|
|
127
|
+
|
|
128
|
+
app = LENAPI()
|
|
129
|
+
service = soap.SOAPService(
|
|
130
|
+
"Calculator",
|
|
131
|
+
target_namespace="https://example.com/calculator",
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
@service.operation
|
|
135
|
+
def add(left: int, right: int) -> int:
|
|
136
|
+
return left + right
|
|
137
|
+
|
|
138
|
+
app.include_router(service.router(path="/soap"))
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
SOAP clients can retrieve the service description at `/soap?wsdl` and send
|
|
142
|
+
SOAP 1.1 XML envelopes to `/soap`. Sync and async operation functions are
|
|
143
|
+
supported. Keep authorization and business validation inside operation
|
|
144
|
+
functions or protect the LenAPI router according to your application policy.
|
|
145
|
+
|
|
70
146
|
## WebSockets
|
|
71
147
|
|
|
72
148
|
WebSockets keep one connection open so a client and server can send messages in
|
|
@@ -1769,10 +1845,21 @@ DATABASE_URL = f"sqlite:///{BASE_DIR / 'lenapi.db'}"
|
|
|
1769
1845
|
# MONGODB_DATABASE = "app_db"
|
|
1770
1846
|
|
|
1771
1847
|
ACTIVATE_ASYNC = False
|
|
1848
|
+
|
|
1849
|
+
# SQLAlchemy connection pool settings (SQLite, MySQL, and PostgreSQL only).
|
|
1850
|
+
# 0 closes physical connections when each request/session returns them to the pool.
|
|
1851
|
+
DATABASE_CONN_MAX_AGE = 0
|
|
1852
|
+
DATABASE_POOL_SIZE = 5
|
|
1853
|
+
DATABASE_MAX_OVERFLOW = 0
|
|
1854
|
+
DATABASE_POOL_TIMEOUT = 30
|
|
1772
1855
|
```
|
|
1773
1856
|
|
|
1774
1857
|
LenAPI chooses the supported synchronous driver for a selected MySQL or PostgreSQL URL. Async access uses `aiosqlite` for SQLite; install `lenapi[async-mysql]` for MySQL or `lenapi[async-postgres]` for PostgreSQL. MongoDB uses its separate sync/async document API.
|
|
1775
1858
|
|
|
1859
|
+
`DATABASE_CONN_MAX_AGE` applies independently to the synchronous and asynchronous SQL connection pools. The default `0` closes a physical connection when the request or database session returns it to the pool; the next database use opens a fresh connection. A positive value, such as `300`, allows connections to be reused and recycles a connection once it reaches that age when it is checked out. It is an age limit, not an exact idle-time timer. In-memory SQLite keeps its connection and uses its dialect-selected pool so its database contents are not lost; the pool size settings are not applied to that special case. These options do not configure MongoDB connections.
|
|
1860
|
+
|
|
1861
|
+
`DATABASE_POOL_SIZE` limits the number of retained connections per engine, while `DATABASE_MAX_OVERFLOW` allows a temporary number of additional concurrent connections. `DATABASE_POOL_TIMEOUT` is how many seconds a checkout waits for a connection before raising a pool timeout. Sync and async engines have separate pools, so account for both when setting database server connection limits. For example, a pool size of 5 with overflow 0 permits up to 5 concurrent connections for each engine in one application worker.
|
|
1862
|
+
|
|
1776
1863
|
### MongoDB documents
|
|
1777
1864
|
|
|
1778
1865
|
Install the official PyMongo driver extra with `python -m pip install -e '.[mongodb]'`. Create a `MongoDatabase` using a MongoDB URI and database name, then bind Pydantic document classes to it. The default collection name is the lower-case document class name; set `collection_name` to override it. MongoDB creates collections on first write; `migration` can also pre-create empty collections for imported `MongoDocument` classes. Document field changes do not use Alembic schema revisions.
|
|
@@ -1972,6 +2059,14 @@ class Enrollment(model.Model):
|
|
|
1972
2059
|
|
|
1973
2060
|
Run the commands from the generated project root. Import application models before migration discovery, normally by importing them in `main.py`.
|
|
1974
2061
|
|
|
2062
|
+
Before deployment, run the configuration check from the project root:
|
|
2063
|
+
|
|
2064
|
+
```bash
|
|
2065
|
+
python lenora.py check --deploy
|
|
2066
|
+
```
|
|
2067
|
+
|
|
2068
|
+
It checks the production-sensitive settings and database URL scheme without printing credential values. It fails for unsafe settings such as `DEBUG=True`, a missing or weak secret, in-memory security storage, or a database type/URL mismatch. A warning about an in-memory cache means that cache entries are local to each process; use a shared backend when the app runs on multiple workers. The command validates configuration, but it does not prove that a remote database or Redis service is reachable.
|
|
2069
|
+
|
|
1975
2070
|
`migration` detects schema changes against imported model metadata, creates a new Alembic revision if needed, and applies pending revisions. It does not upgrade the database when there is no new revision. Use it during development after changing relational models:
|
|
1976
2071
|
|
|
1977
2072
|
```bash
|
|
@@ -1979,6 +2074,14 @@ python lenora.py migration
|
|
|
1979
2074
|
python lenora.py migration --message "add student phone"
|
|
1980
2075
|
```
|
|
1981
2076
|
|
|
2077
|
+
To review the schema diff without creating a revision, applying a migration, or dropping namespaced orphan tables, use:
|
|
2078
|
+
|
|
2079
|
+
```bash
|
|
2080
|
+
python lenora.py migration --dry-run
|
|
2081
|
+
```
|
|
2082
|
+
|
|
2083
|
+
The preview includes project-owned orphan tables/views and reports them as requiring confirmation. A normal `migration` still asks before dropping those objects. For MongoDB, the preview lists expected collections that are missing and project-owned orphan collections, without creating or dropping anything.
|
|
2084
|
+
|
|
1982
2085
|
An existing unversioned SQLite database is adopted only when its schema matches the migration history; adoption preserves its data.
|
|
1983
2086
|
|
|
1984
2087
|
`PositiveIntegerField` and `PositiveBigIntegerField` include a named database `CHECK` constraint. LenAPI prevents Alembic's metadata-copy step from adding that constraint twice, which MySQL rejects as a duplicate constraint name. If a local revision generated by an older LenAPI contains duplicate identical `sa.CheckConstraint(...)` entries, correct or regenerate that unapplied revision before using it. MySQL uses non-transactional DDL, so a failed migration may leave some project tables created even though no revision was recorded. Check `showmigrations` and inspect the project-namespaced tables before retrying. For a disposable database, `delete_migrations` can reset this project's tables and revisions after its confirmation prompt; if the data must be preserved, reconcile the partial schema instead of deleting it.
|
|
@@ -2013,7 +2116,7 @@ python lenora.py repair-migrations
|
|
|
2013
2116
|
python lenora.py delete_migrations
|
|
2014
2117
|
```
|
|
2015
2118
|
|
|
2016
|
-
For MongoDB, `migration` and `migrate` initialize missing framework and imported document collections; they do not create Alembic revisions or migrate document fields. `showmigrations` reports that MongoDB has no Alembic revisions; `repair-migrations` and `clear_migrations` are SQL-only; `delete_migrations` drops all collections after confirmation.
|
|
2119
|
+
For MongoDB, `migration` and `migrate` initialize missing framework and imported document collections; they do not create Alembic revisions or migrate document fields. `migration --dry-run` lists collections that would be created and project-owned orphan collections that would need confirmation before removal. `showmigrations` reports that MongoDB has no Alembic revisions; `repair-migrations` and `clear_migrations` are SQL-only; `delete_migrations` drops all collections after confirmation.
|
|
2017
2120
|
|
|
2018
2121
|
Inside a request, models provide these query helpers:
|
|
2019
2122
|
|
|
@@ -2105,6 +2208,32 @@ has_python_students_async = await Student.afilter(course="Python").exists()
|
|
|
2105
2208
|
|
|
2106
2209
|
`Student.get(...)` builds a single-row lookup; call `.get()` for the model instance or `.exists()` for a boolean. The async single-row counterpart is `await Student.aget(...)`, and its existence check is `await Student.aget(...).exists()`. Multiple matches are an error rather than an arbitrary row selection. `Student.get("field", ...).get(...)` selects one or more columns; one selected column returns a scalar and multiple columns return a mapping. This is a query projection, not a uniqueness constraint. To make the database reject duplicates, declare `unique=True` on the field.
|
|
2107
2210
|
|
|
2211
|
+
### Model signals and commit callbacks
|
|
2212
|
+
|
|
2213
|
+
Connect lifecycle receivers to any `model.Model` subclass or `MongoDocument`. The sender filter is the model class; omit it to receive that signal for all models. Receivers may be synchronous or asynchronous. Async CRUD awaits async receivers automatically.
|
|
2214
|
+
|
|
2215
|
+
```python
|
|
2216
|
+
from lenapi import signals, transaction
|
|
2217
|
+
from app.models import AcademyUser, CreditLedger
|
|
2218
|
+
|
|
2219
|
+
@signals.post_save.connect(sender=AcademyUser)
|
|
2220
|
+
def grant_signup_credits(sender, instance, created, **kwargs):
|
|
2221
|
+
if created:
|
|
2222
|
+
CreditLedger.create(
|
|
2223
|
+
user_id=instance.id,
|
|
2224
|
+
amount=100,
|
|
2225
|
+
reason="signup_bonus",
|
|
2226
|
+
)
|
|
2227
|
+
|
|
2228
|
+
with transaction.atomic(app.database):
|
|
2229
|
+
user = AcademyUser.create(email="ada@example.com")
|
|
2230
|
+
transaction.on_commit(send_welcome_email, user.email)
|
|
2231
|
+
```
|
|
2232
|
+
|
|
2233
|
+
LenAPI provides `pre_save`, `post_save`, `pre_delete`, and `post_delete`. Save receivers receive `instance`, `created`, `using`, and `update_fields`; delete receivers receive `instance` and `using`. Extra values are available through `**kwargs`. A `post_save` receiver inside `transaction.atomic(...)` runs after the row is flushed but before the outer commit, so database writes made by that receiver share the transaction. Use `transaction.on_commit(callback, *args, **kwargs)` for effects that should wait for a successful commit, such as scheduling an email. A rollback discards callbacks registered in that block; callbacks from nested atomic blocks wait for the outer commit. Outside an atomic block, `on_commit` runs immediately.
|
|
2234
|
+
|
|
2235
|
+
Async receivers work with async CRUD, and async `on_commit` callbacks are awaited after `async with transaction.atomic(app.async_database)` commits. Use synchronous receivers and callbacks with synchronous atomic blocks. Receiver exceptions propagate; inside an atomic block they roll back the transaction. Instance and queryset row deletes emit delete signals. `Model.all().delete()` drops the table and does not emit row signals.
|
|
2236
|
+
|
|
2108
2237
|
### Fetch related records
|
|
2109
2238
|
|
|
2110
2239
|
With a `ForeignKeyField` such as `Student.classroom_id`, sync code can resolve the target row using `.special("classroom_id")`. It returns a proxy where that same attribute contains the related `Classroom` instance (or `None` if the foreign key is null):
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"""lenApi: a small, typed ASGI web framework."""
|
|
2
2
|
|
|
3
3
|
import sys
|
|
4
|
+
from importlib import import_module
|
|
4
5
|
|
|
5
6
|
if sys.version_info < (3, 11):
|
|
6
7
|
raise RuntimeError(
|
|
@@ -8,7 +9,14 @@ if sys.version_info < (3, 11):
|
|
|
8
9
|
"on 2026-10-01 and is no longer supported."
|
|
9
10
|
)
|
|
10
11
|
|
|
11
|
-
__version__ = "0.1.4.
|
|
12
|
+
__version__ = "0.1.4.9"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def __getattr__(name: str):
|
|
16
|
+
"""Load optional protocol modules only when explicitly requested."""
|
|
17
|
+
if name in {"graphql", "soap"}:
|
|
18
|
+
return import_module(f".{name}", __name__)
|
|
19
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
12
20
|
|
|
13
21
|
from .application import Application, LENAPI, Router
|
|
14
22
|
from .background import BackgroundQueue, BackgroundTasks
|
|
@@ -18,6 +26,7 @@ from .auth import SocialAuth
|
|
|
18
26
|
from .authorization import require_owner, require_permission, require_role
|
|
19
27
|
from .database import AsyncDatabase, Database
|
|
20
28
|
from .transaction import transaction
|
|
29
|
+
from . import signals
|
|
21
30
|
from .mongodb import MongoDatabase, MongoDocument, MultipleDocumentsFound
|
|
22
31
|
from .parameters import Body, File
|
|
23
32
|
from .logging import get_logger, logger
|
|
@@ -97,8 +106,9 @@ from .security import (
|
|
|
97
106
|
from . import model
|
|
98
107
|
|
|
99
108
|
__all__ = [
|
|
100
|
-
"Application", "LENAPI", "Router", "Depends", "BackgroundTasks", "BackgroundQueue", "Cache", "Faker", "OpenAI", "Ollama", "CORSMiddleware", "DocsAuthMiddleware", "GZipMiddleware", "RequestIDMiddleware", "TimingMiddleware", "require_role", "require_permission", "require_owner", "Database", "AsyncDatabase", "transaction", "MongoDatabase", "MongoDocument", "MultipleDocumentsFound", "Body", "File", "Model", "AdminUser", "AutoField", "logger", "get_logger", "WebSocket", "WebSocketConnection", "WebSocketDisconnect", "WebSocketService",
|
|
109
|
+
"Application", "LENAPI", "Router", "Depends", "BackgroundTasks", "BackgroundQueue", "Cache", "Faker", "OpenAI", "Ollama", "CORSMiddleware", "DocsAuthMiddleware", "GZipMiddleware", "RequestIDMiddleware", "TimingMiddleware", "require_role", "require_permission", "require_owner", "Database", "AsyncDatabase", "transaction", "signals", "MongoDatabase", "MongoDocument", "MultipleDocumentsFound", "Body", "File", "Model", "AdminUser", "AutoField", "logger", "get_logger", "WebSocket", "WebSocketConnection", "WebSocketDisconnect", "WebSocketService",
|
|
101
110
|
"IntegerField", "PositiveIntegerField", "BigIntField", "BigIntegerField", "PositiveBigIntegerField", "DecimalField", "StringField", "EmailField", "IPField", "PhoneField", "TextField", "UUIDField", "ImageField", "FileField", "FileImageField", "URLField", "BooleanField", "FloatField", "User",
|
|
102
111
|
"DateTimeField", "DateField", "TimeField", "DurationField", "JSONField", "ForeignKeyField", "OneToOneField", "OneToManyField", "ManyToManyField", "Count", "Sum", "Min", "Max", "Avg", "Request", "UploadFile", "Response", "JSONResponse",
|
|
103
112
|
"HTTPException", "JWTAuth", "APIKeyAuth", "BasicAuth", "CSRFProtect", "SessionAuth", "OpaqueBearerAuth", "HMACAuth", "OIDCAuth", "WebhookAuth", "hmac_request_signature", "session_auth", "opaque_bearer_auth", "hmac_auth", "oidc_auth", "webhook_auth", "create_authenticator", "authentication", "SocialAuth", "hash_password", "verify_password", "make_password", "check_password", "make_api_key", "hash_api_key", "UNSET", "model", "CASCADE", "SET_NULL", "PROTECT", "cascade", "null", "protected",
|
|
113
|
+
"graphql", "soap",
|
|
104
114
|
]
|
|
@@ -1384,6 +1384,12 @@ class LENAPI(Application):
|
|
|
1384
1384
|
database_type = str(getattr(project_settings, "DATABASE_TYPE", "sqlite")).lower()
|
|
1385
1385
|
database_url = getattr(project_settings, "DATABASE_URL", None)
|
|
1386
1386
|
activate_async = bool(getattr(project_settings, "ACTIVATE_ASYNC", True))
|
|
1387
|
+
database_pool_options = {
|
|
1388
|
+
"connection_max_age": getattr(project_settings, "DATABASE_CONN_MAX_AGE", 0),
|
|
1389
|
+
"pool_size": getattr(project_settings, "DATABASE_POOL_SIZE", 5),
|
|
1390
|
+
"max_overflow": getattr(project_settings, "DATABASE_MAX_OVERFLOW", 0),
|
|
1391
|
+
"pool_timeout": getattr(project_settings, "DATABASE_POOL_TIMEOUT", 30),
|
|
1392
|
+
}
|
|
1387
1393
|
|
|
1388
1394
|
if database_type not in {"sqlite", "mysql", "postgres", "postgresql", "mongodb"}:
|
|
1389
1395
|
raise ValueError(
|
|
@@ -1414,7 +1420,10 @@ class LENAPI(Application):
|
|
|
1414
1420
|
f"DATABASE_URL uses '{backend}', "
|
|
1415
1421
|
f"but DATABASE_TYPE is '{database_type}'"
|
|
1416
1422
|
)
|
|
1417
|
-
configured_database = Database(
|
|
1423
|
+
configured_database = Database(
|
|
1424
|
+
sync_url.render_as_string(hide_password=False),
|
|
1425
|
+
**database_pool_options,
|
|
1426
|
+
)
|
|
1418
1427
|
if configured_async_database is None and activate_async:
|
|
1419
1428
|
async_drivers = {
|
|
1420
1429
|
"sqlite": "sqlite+aiosqlite",
|
|
@@ -1425,7 +1434,10 @@ class LENAPI(Application):
|
|
|
1425
1434
|
drivername=async_drivers[expected]
|
|
1426
1435
|
)
|
|
1427
1436
|
try:
|
|
1428
|
-
configured_async_database = AsyncDatabase(
|
|
1437
|
+
configured_async_database = AsyncDatabase(
|
|
1438
|
+
async_url.render_as_string(hide_password=False),
|
|
1439
|
+
**database_pool_options,
|
|
1440
|
+
)
|
|
1429
1441
|
except (ImportError, ModuleNotFoundError) as exc:
|
|
1430
1442
|
extras = {
|
|
1431
1443
|
"mysql": "async-mysql",
|