lenapi 0.1.4.1__tar.gz → 0.1.4.3__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.1 → lenapi-0.1.4.3}/PKG-INFO +75 -32
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/README.md +74 -31
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/__init__.py +3 -2
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/application.py +83 -6
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/authentication.py +62 -4
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/cli.py +219 -2
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/model.py +2 -1
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/models.py +465 -21
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/security.py +245 -28
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi.egg-info/PKG-INFO +75 -32
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/pyproject.toml +1 -1
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/tests/test_framework_features.py +221 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/tests/test_user_model_extension.py +24 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/LICENSE +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/admin.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/auth.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/authorization.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/background.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/concurrency.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/database.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/dependencies.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/docs_guard.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/logging.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/middleware.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/mongodb.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/openapi.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/parameters.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/project.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/request.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/response.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/security_store.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/sentinels.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/service.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/throttling.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi/transaction.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi.egg-info/SOURCES.txt +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi.egg-info/dependency_links.txt +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi.egg-info/entry_points.txt +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi.egg-info/requires.txt +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi.egg-info/top_level.txt +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/lenapi_bootstrap.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/setup.cfg +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/tests/test_admin_console.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/tests/test_cli_settings_recovery.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/tests/test_docs_guard.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/tests/test_media_upload.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/tests/test_mongodb.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/tests/test_platform_services.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/tests/test_project_isolation.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/tests/test_security_patch.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/tests/test_sentinels.py +0 -0
- {lenapi-0.1.4.1 → lenapi-0.1.4.3}/tests/test_throttle.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.3
|
|
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>
|
|
@@ -1885,11 +1885,17 @@ from lenapi import User, model
|
|
|
1885
1885
|
|
|
1886
1886
|
class Classroom(model.Model):
|
|
1887
1887
|
name = model.StringField(max_length=120)
|
|
1888
|
+
learners = model.OneToManyField("Learner", foreign_key="classroom_id")
|
|
1888
1889
|
|
|
1889
1890
|
class Student(model.Model):
|
|
1890
1891
|
person_name = model.StringField(max_length=120, unique=True)
|
|
1891
1892
|
course = model.StringField(max_length=120)
|
|
1892
|
-
classroom_id = model.ForeignKeyField(
|
|
1893
|
+
classroom_id = model.ForeignKeyField(
|
|
1894
|
+
Classroom,
|
|
1895
|
+
relation_name="classroom",
|
|
1896
|
+
nullable=True,
|
|
1897
|
+
model=model.null,
|
|
1898
|
+
)
|
|
1893
1899
|
|
|
1894
1900
|
class Course(model.Model):
|
|
1895
1901
|
name = model.StringField(max_length=120)
|
|
@@ -1908,11 +1914,24 @@ class Invoice(model.Model):
|
|
|
1908
1914
|
user_id = model.ForeignKeyField("user.id", model=model.protected)
|
|
1909
1915
|
```
|
|
1910
1916
|
|
|
1917
|
+
`ForeignKeyField` accepts either a model class or the existing `"table.column"` string target. With an `_id` field name, LenAPI resolves its related object through the matching attribute (for example, `student.classroom`). Use `relation_name` when you want to choose that attribute explicitly. `.special()` accepts either the foreign-key column name or relation name and returns the related model through that name:
|
|
1918
|
+
|
|
1919
|
+
```python
|
|
1920
|
+
student = Student.get(id=student_id).special("classroom")
|
|
1921
|
+
print(student.classroom.name)
|
|
1922
|
+
|
|
1923
|
+
# The original string target remains supported:
|
|
1924
|
+
class LegacyStudent(model.Model):
|
|
1925
|
+
classroom_id = model.ForeignKeyField("classroom.id", relation_name="classroom")
|
|
1926
|
+
```
|
|
1927
|
+
|
|
1911
1928
|
Table names are inferred from model class names in lowercase (`Student` becomes `student`); no table-name declaration is needed. Import `model` from `lenapi` and access the model base class, fields, and relationship behaviors through it, such as `model.Model`, `model.StringField`, and `model.ForeignKeyField`.
|
|
1912
1929
|
|
|
1913
1930
|
`model.Model` is the base class for SQL-backed models. Subclass it to declare a table; each field assignment declares a database column, and the framework supplies an integer `id` primary key unless you define one yourself. Field declarations describe storage and database constraints; use Pydantic schemas to validate API input.
|
|
1914
1931
|
|
|
1915
|
-
|
|
1932
|
+
`User` and `AdminUser` are reserved LenAPI model names. If an application declares a separate model with either name, migration stops with guidance to rename the application model before changing the database. Use a distinct name such as `Customer` or `ProjectAdmin`; to extend the built-in user model, subclass LenAPI's `User` without declaring a separate table.
|
|
1933
|
+
|
|
1934
|
+
The field helpers include `AutoField`, signed `IntegerField` and `BigIntegerField`/`BigIntField`, nonnegative `PositiveIntegerField` and `PositiveBigIntegerField`, `StringField`, `TextField`, `EmailField`, `PhoneField`, `IPField`, `URLField`, `BooleanField`, `FloatField`, `DecimalField`, `DateField`, `TimeField`, `DateTimeField`, `DurationField`, `JSONField`/`Json`, `UUIDField`, `ImageField`, `FileField`, `FileImageField`, `ForeignKeyField`, `OneToOneField`, `OneToManyField`, and `ManyToManyField`. Fields normally default to `nullable=True` and `blank=True`; `null=` is accepted as an alias for `nullable=`. `BooleanField` defaults to `True`. `JSONField` and its alias `Json` store JSON-compatible Python values. Use a factory such as `default=dict` for a fresh mutable value on each new row:
|
|
1916
1935
|
|
|
1917
1936
|
```python
|
|
1918
1937
|
class Student(model.Model):
|
|
@@ -2128,13 +2147,11 @@ if classroom is not None:
|
|
|
2128
2147
|
print(classroom.name)
|
|
2129
2148
|
```
|
|
2130
2149
|
|
|
2131
|
-
|
|
2150
|
+
Use the async relationship loader to resolve foreign keys and one-to-one fields in a batch:
|
|
2132
2151
|
|
|
2133
2152
|
```python
|
|
2134
|
-
student = await Student.
|
|
2135
|
-
classroom = None
|
|
2136
|
-
if student is not None and student.classroom_id is not None:
|
|
2137
|
-
classroom = await Classroom.aget(id=student.classroom_id)
|
|
2153
|
+
student = await Student.afilter(id=1).special("classroom_id").all()
|
|
2154
|
+
classroom = student[0].classroom_id if student else None
|
|
2138
2155
|
```
|
|
2139
2156
|
|
|
2140
2157
|
For `ManyToManyField`, the related collection is available as an attribute. In sync code, call `.all()` to get its related model instances:
|
|
@@ -2147,30 +2164,30 @@ courses = teacher.courses.all()
|
|
|
2147
2164
|
print([course.name for course in courses])
|
|
2148
2165
|
```
|
|
2149
2166
|
|
|
2150
|
-
In async routes,
|
|
2167
|
+
In async routes, use `.amany()` on loaded rows or `.many(...).all()` on the query. LenAPI eagerly loads the collection for you:
|
|
2151
2168
|
|
|
2152
2169
|
```python
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
from lenapi import HTTPException
|
|
2157
|
-
from app.models import Teacher
|
|
2170
|
+
teachers = await Teacher.afilter(id=1).many("courses").all()
|
|
2171
|
+
courses = teachers[0].courses.all() if teachers else []
|
|
2172
|
+
```
|
|
2158
2173
|
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2174
|
+
Declare the relationships in `app/models.py` and run `python lenora.py migration` before querying them. For one-to-many collections, declare `OneToManyField` on the parent and use `.batch()` / `.abatch()`. Sync and async filter and get-all queries support these loaders:
|
|
2175
|
+
|
|
2176
|
+
```python
|
|
2177
|
+
class Classroom(model.Model):
|
|
2178
|
+
learners = model.OneToManyField("Learner", foreign_key="classroom_id")
|
|
2179
|
+
|
|
2180
|
+
# Sync filtered query and all-row query
|
|
2181
|
+
rooms = Classroom.filter(name="Room A").batch("learners").all()
|
|
2182
|
+
all_rooms = Classroom.get.all().batch("learners")
|
|
2183
|
+
|
|
2184
|
+
# Async equivalents
|
|
2185
|
+
rooms = await Classroom.afilter(name="Room A").batch("learners").all()
|
|
2186
|
+
all_rooms = await Classroom.aget.all()
|
|
2187
|
+
all_rooms = await all_rooms.abatch("learners")
|
|
2171
2188
|
```
|
|
2172
2189
|
|
|
2173
|
-
|
|
2190
|
+
Use `.special("foreign_key")` for a foreign-key or one-to-one relation, `.many("collection")` for a many-to-many collection, and `.batch("collection")` for a one-to-many collection. Their async counterparts are `.aspecial()`, `.amany()`, and `.abatch()` when loading an already retrieved list. Async relationship loading requires `ACTIVATE_ASYNC = True` and the matching async driver.
|
|
2174
2191
|
|
|
2175
2192
|
`filter(...)` accepts equality filters and lookups such as `course__icontains="py"`, `id__gte=10`, `id__in=[1, 2]`, and `classroom_id__isnull=True`. Supported lookup suffixes are `exact`, `iexact`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `notin`, `contains`, `icontains`, `startswith`, `istartswith`, `endswith`, `iendswith`, and `isnull`. Query methods include `.values(...)`, `.order(field)` (prefix with `-` for descending), `.limit(n)`, `.offset(n)`, and terminal operations `.all()`, `.first()`, `.one_or_none()`, `.count()`, `.aggregate(...)`, and `.delete()`. Async query builders use `afilter()`, `asearch()`, and `asearch_any()`; await terminal methods such as `.all()`, `.get()`, `.count()`, `.aggregate()`, or `.delete()`.
|
|
2176
2193
|
|
|
@@ -2295,6 +2312,31 @@ student, created = Student.get_or_create(
|
|
|
2295
2312
|
|
|
2296
2313
|
`get_or_404`, `update_or_404`, and `delete_or_404` raise `HTTPException(404, ...)` when no record matches, which lenApi returns as an HTTP 404 response. `create_update` creates a missing row or updates an existing one and returns the model instance. `get_or_create` returns `(instance, created)`, where `created` is a boolean.
|
|
2297
2314
|
|
|
2315
|
+
Async routes can use the matching `a`-prefixed helpers with `await`:
|
|
2316
|
+
|
|
2317
|
+
```python
|
|
2318
|
+
student = await Student.aget_or_404(id=student_id)
|
|
2319
|
+
|
|
2320
|
+
student = await Student.acreate_update(
|
|
2321
|
+
defaults={"course": "Python"},
|
|
2322
|
+
person_name="Ifeanyi",
|
|
2323
|
+
)
|
|
2324
|
+
|
|
2325
|
+
student = await Student.aupdate_or_404(
|
|
2326
|
+
defaults={"course": "Java"},
|
|
2327
|
+
person_name="Ifeanyi",
|
|
2328
|
+
)
|
|
2329
|
+
|
|
2330
|
+
await Student.adelete_or_404(person_name="Ifeanyi")
|
|
2331
|
+
|
|
2332
|
+
student, created = await Student.aget_or_create(
|
|
2333
|
+
defaults={"course": "Python"},
|
|
2334
|
+
person_name="Ifeanyi",
|
|
2335
|
+
)
|
|
2336
|
+
```
|
|
2337
|
+
|
|
2338
|
+
The async helpers are `aget_or_404`, `acreate_update`, `aupdate_or_404`, `adelete_or_404`, and `aget_or_create`. Pass `session=...` when using an explicit `AsyncSession`; otherwise they use the active LenAPI request session. The `*_or_404` methods raise `HTTPException(404, ...)` when no row matches.
|
|
2339
|
+
|
|
2298
2340
|
For a declared foreign-key column, `.special("field_name")` resolves its related model and exposes it under that same field name:
|
|
2299
2341
|
|
|
2300
2342
|
```python
|
|
@@ -2304,7 +2346,7 @@ classroom_name = student.classroom_id.name
|
|
|
2304
2346
|
|
|
2305
2347
|
Here, the field name must be a `ForeignKeyField` targeting a registered lenApi model. The value at `student.classroom_id` is the related model instance; the project example defines this as `classroom_id`.
|
|
2306
2348
|
|
|
2307
|
-
Use `OneToOneField` when a dependent row must have exactly one owner and the owner may have at most one dependent row. It is a foreign key with a database unique constraint.
|
|
2349
|
+
Use `OneToOneField` when a dependent row must have exactly one owner and the owner may have at most one dependent row. It is a foreign key with a database unique constraint. Use `OneToManyField` on the parent side to expose a child collection; the child still declares the matching `ForeignKeyField`:
|
|
2308
2350
|
|
|
2309
2351
|
```python
|
|
2310
2352
|
class Classroom(model.Model):
|
|
@@ -2318,15 +2360,16 @@ class LearnerProfile(model.Model):
|
|
|
2318
2360
|
learner_id = model.OneToOneField("learner.id", nullable=False)
|
|
2319
2361
|
biography = model.TextField()
|
|
2320
2362
|
|
|
2321
|
-
|
|
2322
|
-
|
|
2363
|
+
classrooms = Classroom.get(id=1).batch("learners").all()
|
|
2364
|
+
classroom = classrooms[0] if classrooms else None
|
|
2365
|
+
learners = classroom.learners if classroom else []
|
|
2323
2366
|
learner = Learner.get_or_404(id=1).special("classroom_id")
|
|
2324
2367
|
print(learner.classroom_id.name)
|
|
2325
2368
|
|
|
2326
2369
|
profile = LearnerProfile.get(learner_id=learner.id).get()
|
|
2327
2370
|
```
|
|
2328
2371
|
|
|
2329
|
-
For many-to-many queries, load the owning model
|
|
2372
|
+
For many-to-many queries, load the owning model with `.many("courses")` or `.amany("courses")`, then access its set-like collection. `OneToManyField` collections use `.batch("learners")` or `.abatch("learners")`.
|
|
2330
2373
|
|
|
2331
2374
|
Choose what happens to dependent records when their referenced model is deleted with `model`:
|
|
2332
2375
|
|
|
@@ -2353,7 +2396,7 @@ teacher.courses.remove(course)
|
|
|
2353
2396
|
teacher.save()
|
|
2354
2397
|
```
|
|
2355
2398
|
|
|
2356
|
-
Pass `table_name="teacher_courses"` to `ManyToManyField` to choose the association table name. Use `back_populates="teachers"` to pair it with a reciprocal `teachers = ManyToManyField("Teacher", table_name="teacher_courses", back_populates="courses")` field on `Course
|
|
2399
|
+
Pass `table_name="teacher_courses"` to `ManyToManyField` to choose the association table name. Use `back_populates="teachers"` to pair it with a reciprocal `teachers = ManyToManyField("Teacher", table_name="teacher_courses", back_populates="courses")` field on `Course`, or use `related_name="teachers"` to declare a reverse collection from one side.
|
|
2357
2400
|
|
|
2358
2401
|
```python
|
|
2359
2402
|
from lenapi import Application, Database
|
|
@@ -1833,11 +1833,17 @@ from lenapi import User, model
|
|
|
1833
1833
|
|
|
1834
1834
|
class Classroom(model.Model):
|
|
1835
1835
|
name = model.StringField(max_length=120)
|
|
1836
|
+
learners = model.OneToManyField("Learner", foreign_key="classroom_id")
|
|
1836
1837
|
|
|
1837
1838
|
class Student(model.Model):
|
|
1838
1839
|
person_name = model.StringField(max_length=120, unique=True)
|
|
1839
1840
|
course = model.StringField(max_length=120)
|
|
1840
|
-
classroom_id = model.ForeignKeyField(
|
|
1841
|
+
classroom_id = model.ForeignKeyField(
|
|
1842
|
+
Classroom,
|
|
1843
|
+
relation_name="classroom",
|
|
1844
|
+
nullable=True,
|
|
1845
|
+
model=model.null,
|
|
1846
|
+
)
|
|
1841
1847
|
|
|
1842
1848
|
class Course(model.Model):
|
|
1843
1849
|
name = model.StringField(max_length=120)
|
|
@@ -1856,11 +1862,24 @@ class Invoice(model.Model):
|
|
|
1856
1862
|
user_id = model.ForeignKeyField("user.id", model=model.protected)
|
|
1857
1863
|
```
|
|
1858
1864
|
|
|
1865
|
+
`ForeignKeyField` accepts either a model class or the existing `"table.column"` string target. With an `_id` field name, LenAPI resolves its related object through the matching attribute (for example, `student.classroom`). Use `relation_name` when you want to choose that attribute explicitly. `.special()` accepts either the foreign-key column name or relation name and returns the related model through that name:
|
|
1866
|
+
|
|
1867
|
+
```python
|
|
1868
|
+
student = Student.get(id=student_id).special("classroom")
|
|
1869
|
+
print(student.classroom.name)
|
|
1870
|
+
|
|
1871
|
+
# The original string target remains supported:
|
|
1872
|
+
class LegacyStudent(model.Model):
|
|
1873
|
+
classroom_id = model.ForeignKeyField("classroom.id", relation_name="classroom")
|
|
1874
|
+
```
|
|
1875
|
+
|
|
1859
1876
|
Table names are inferred from model class names in lowercase (`Student` becomes `student`); no table-name declaration is needed. Import `model` from `lenapi` and access the model base class, fields, and relationship behaviors through it, such as `model.Model`, `model.StringField`, and `model.ForeignKeyField`.
|
|
1860
1877
|
|
|
1861
1878
|
`model.Model` is the base class for SQL-backed models. Subclass it to declare a table; each field assignment declares a database column, and the framework supplies an integer `id` primary key unless you define one yourself. Field declarations describe storage and database constraints; use Pydantic schemas to validate API input.
|
|
1862
1879
|
|
|
1863
|
-
|
|
1880
|
+
`User` and `AdminUser` are reserved LenAPI model names. If an application declares a separate model with either name, migration stops with guidance to rename the application model before changing the database. Use a distinct name such as `Customer` or `ProjectAdmin`; to extend the built-in user model, subclass LenAPI's `User` without declaring a separate table.
|
|
1881
|
+
|
|
1882
|
+
The field helpers include `AutoField`, signed `IntegerField` and `BigIntegerField`/`BigIntField`, nonnegative `PositiveIntegerField` and `PositiveBigIntegerField`, `StringField`, `TextField`, `EmailField`, `PhoneField`, `IPField`, `URLField`, `BooleanField`, `FloatField`, `DecimalField`, `DateField`, `TimeField`, `DateTimeField`, `DurationField`, `JSONField`/`Json`, `UUIDField`, `ImageField`, `FileField`, `FileImageField`, `ForeignKeyField`, `OneToOneField`, `OneToManyField`, and `ManyToManyField`. Fields normally default to `nullable=True` and `blank=True`; `null=` is accepted as an alias for `nullable=`. `BooleanField` defaults to `True`. `JSONField` and its alias `Json` store JSON-compatible Python values. Use a factory such as `default=dict` for a fresh mutable value on each new row:
|
|
1864
1883
|
|
|
1865
1884
|
```python
|
|
1866
1885
|
class Student(model.Model):
|
|
@@ -2076,13 +2095,11 @@ if classroom is not None:
|
|
|
2076
2095
|
print(classroom.name)
|
|
2077
2096
|
```
|
|
2078
2097
|
|
|
2079
|
-
|
|
2098
|
+
Use the async relationship loader to resolve foreign keys and one-to-one fields in a batch:
|
|
2080
2099
|
|
|
2081
2100
|
```python
|
|
2082
|
-
student = await Student.
|
|
2083
|
-
classroom = None
|
|
2084
|
-
if student is not None and student.classroom_id is not None:
|
|
2085
|
-
classroom = await Classroom.aget(id=student.classroom_id)
|
|
2101
|
+
student = await Student.afilter(id=1).special("classroom_id").all()
|
|
2102
|
+
classroom = student[0].classroom_id if student else None
|
|
2086
2103
|
```
|
|
2087
2104
|
|
|
2088
2105
|
For `ManyToManyField`, the related collection is available as an attribute. In sync code, call `.all()` to get its related model instances:
|
|
@@ -2095,30 +2112,30 @@ courses = teacher.courses.all()
|
|
|
2095
2112
|
print([course.name for course in courses])
|
|
2096
2113
|
```
|
|
2097
2114
|
|
|
2098
|
-
In async routes,
|
|
2115
|
+
In async routes, use `.amany()` on loaded rows or `.many(...).all()` on the query. LenAPI eagerly loads the collection for you:
|
|
2099
2116
|
|
|
2100
2117
|
```python
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
from lenapi import HTTPException
|
|
2105
|
-
from app.models import Teacher
|
|
2118
|
+
teachers = await Teacher.afilter(id=1).many("courses").all()
|
|
2119
|
+
courses = teachers[0].courses.all() if teachers else []
|
|
2120
|
+
```
|
|
2106
2121
|
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2122
|
+
Declare the relationships in `app/models.py` and run `python lenora.py migration` before querying them. For one-to-many collections, declare `OneToManyField` on the parent and use `.batch()` / `.abatch()`. Sync and async filter and get-all queries support these loaders:
|
|
2123
|
+
|
|
2124
|
+
```python
|
|
2125
|
+
class Classroom(model.Model):
|
|
2126
|
+
learners = model.OneToManyField("Learner", foreign_key="classroom_id")
|
|
2127
|
+
|
|
2128
|
+
# Sync filtered query and all-row query
|
|
2129
|
+
rooms = Classroom.filter(name="Room A").batch("learners").all()
|
|
2130
|
+
all_rooms = Classroom.get.all().batch("learners")
|
|
2131
|
+
|
|
2132
|
+
# Async equivalents
|
|
2133
|
+
rooms = await Classroom.afilter(name="Room A").batch("learners").all()
|
|
2134
|
+
all_rooms = await Classroom.aget.all()
|
|
2135
|
+
all_rooms = await all_rooms.abatch("learners")
|
|
2119
2136
|
```
|
|
2120
2137
|
|
|
2121
|
-
|
|
2138
|
+
Use `.special("foreign_key")` for a foreign-key or one-to-one relation, `.many("collection")` for a many-to-many collection, and `.batch("collection")` for a one-to-many collection. Their async counterparts are `.aspecial()`, `.amany()`, and `.abatch()` when loading an already retrieved list. Async relationship loading requires `ACTIVATE_ASYNC = True` and the matching async driver.
|
|
2122
2139
|
|
|
2123
2140
|
`filter(...)` accepts equality filters and lookups such as `course__icontains="py"`, `id__gte=10`, `id__in=[1, 2]`, and `classroom_id__isnull=True`. Supported lookup suffixes are `exact`, `iexact`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `notin`, `contains`, `icontains`, `startswith`, `istartswith`, `endswith`, `iendswith`, and `isnull`. Query methods include `.values(...)`, `.order(field)` (prefix with `-` for descending), `.limit(n)`, `.offset(n)`, and terminal operations `.all()`, `.first()`, `.one_or_none()`, `.count()`, `.aggregate(...)`, and `.delete()`. Async query builders use `afilter()`, `asearch()`, and `asearch_any()`; await terminal methods such as `.all()`, `.get()`, `.count()`, `.aggregate()`, or `.delete()`.
|
|
2124
2141
|
|
|
@@ -2243,6 +2260,31 @@ student, created = Student.get_or_create(
|
|
|
2243
2260
|
|
|
2244
2261
|
`get_or_404`, `update_or_404`, and `delete_or_404` raise `HTTPException(404, ...)` when no record matches, which lenApi returns as an HTTP 404 response. `create_update` creates a missing row or updates an existing one and returns the model instance. `get_or_create` returns `(instance, created)`, where `created` is a boolean.
|
|
2245
2262
|
|
|
2263
|
+
Async routes can use the matching `a`-prefixed helpers with `await`:
|
|
2264
|
+
|
|
2265
|
+
```python
|
|
2266
|
+
student = await Student.aget_or_404(id=student_id)
|
|
2267
|
+
|
|
2268
|
+
student = await Student.acreate_update(
|
|
2269
|
+
defaults={"course": "Python"},
|
|
2270
|
+
person_name="Ifeanyi",
|
|
2271
|
+
)
|
|
2272
|
+
|
|
2273
|
+
student = await Student.aupdate_or_404(
|
|
2274
|
+
defaults={"course": "Java"},
|
|
2275
|
+
person_name="Ifeanyi",
|
|
2276
|
+
)
|
|
2277
|
+
|
|
2278
|
+
await Student.adelete_or_404(person_name="Ifeanyi")
|
|
2279
|
+
|
|
2280
|
+
student, created = await Student.aget_or_create(
|
|
2281
|
+
defaults={"course": "Python"},
|
|
2282
|
+
person_name="Ifeanyi",
|
|
2283
|
+
)
|
|
2284
|
+
```
|
|
2285
|
+
|
|
2286
|
+
The async helpers are `aget_or_404`, `acreate_update`, `aupdate_or_404`, `adelete_or_404`, and `aget_or_create`. Pass `session=...` when using an explicit `AsyncSession`; otherwise they use the active LenAPI request session. The `*_or_404` methods raise `HTTPException(404, ...)` when no row matches.
|
|
2287
|
+
|
|
2246
2288
|
For a declared foreign-key column, `.special("field_name")` resolves its related model and exposes it under that same field name:
|
|
2247
2289
|
|
|
2248
2290
|
```python
|
|
@@ -2252,7 +2294,7 @@ classroom_name = student.classroom_id.name
|
|
|
2252
2294
|
|
|
2253
2295
|
Here, the field name must be a `ForeignKeyField` targeting a registered lenApi model. The value at `student.classroom_id` is the related model instance; the project example defines this as `classroom_id`.
|
|
2254
2296
|
|
|
2255
|
-
Use `OneToOneField` when a dependent row must have exactly one owner and the owner may have at most one dependent row. It is a foreign key with a database unique constraint.
|
|
2297
|
+
Use `OneToOneField` when a dependent row must have exactly one owner and the owner may have at most one dependent row. It is a foreign key with a database unique constraint. Use `OneToManyField` on the parent side to expose a child collection; the child still declares the matching `ForeignKeyField`:
|
|
2256
2298
|
|
|
2257
2299
|
```python
|
|
2258
2300
|
class Classroom(model.Model):
|
|
@@ -2266,15 +2308,16 @@ class LearnerProfile(model.Model):
|
|
|
2266
2308
|
learner_id = model.OneToOneField("learner.id", nullable=False)
|
|
2267
2309
|
biography = model.TextField()
|
|
2268
2310
|
|
|
2269
|
-
|
|
2270
|
-
|
|
2311
|
+
classrooms = Classroom.get(id=1).batch("learners").all()
|
|
2312
|
+
classroom = classrooms[0] if classrooms else None
|
|
2313
|
+
learners = classroom.learners if classroom else []
|
|
2271
2314
|
learner = Learner.get_or_404(id=1).special("classroom_id")
|
|
2272
2315
|
print(learner.classroom_id.name)
|
|
2273
2316
|
|
|
2274
2317
|
profile = LearnerProfile.get(learner_id=learner.id).get()
|
|
2275
2318
|
```
|
|
2276
2319
|
|
|
2277
|
-
For many-to-many queries, load the owning model
|
|
2320
|
+
For many-to-many queries, load the owning model with `.many("courses")` or `.amany("courses")`, then access its set-like collection. `OneToManyField` collections use `.batch("learners")` or `.abatch("learners")`.
|
|
2278
2321
|
|
|
2279
2322
|
Choose what happens to dependent records when their referenced model is deleted with `model`:
|
|
2280
2323
|
|
|
@@ -2301,7 +2344,7 @@ teacher.courses.remove(course)
|
|
|
2301
2344
|
teacher.save()
|
|
2302
2345
|
```
|
|
2303
2346
|
|
|
2304
|
-
Pass `table_name="teacher_courses"` to `ManyToManyField` to choose the association table name. Use `back_populates="teachers"` to pair it with a reciprocal `teachers = ManyToManyField("Teacher", table_name="teacher_courses", back_populates="courses")` field on `Course
|
|
2347
|
+
Pass `table_name="teacher_courses"` to `ManyToManyField` to choose the association table name. Use `back_populates="teachers"` to pair it with a reciprocal `teachers = ManyToManyField("Teacher", table_name="teacher_courses", back_populates="courses")` field on `Course`, or use `related_name="teachers"` to declare a reverse collection from one side.
|
|
2305
2348
|
|
|
2306
2349
|
```python
|
|
2307
2350
|
from lenapi import Application, Database
|
|
@@ -8,7 +8,7 @@ if sys.version_info < (3, 11):
|
|
|
8
8
|
"on 2026-10-01 and is no longer supported."
|
|
9
9
|
)
|
|
10
10
|
|
|
11
|
-
__version__ = "0.1.4.
|
|
11
|
+
__version__ = "0.1.4.3"
|
|
12
12
|
|
|
13
13
|
from .application import Application, LENAPI, Router
|
|
14
14
|
from .background import BackgroundQueue, BackgroundTasks
|
|
@@ -46,6 +46,7 @@ from .models import (
|
|
|
46
46
|
PositiveIntegerField,
|
|
47
47
|
JSONField,
|
|
48
48
|
ManyToManyField,
|
|
49
|
+
OneToManyField,
|
|
49
50
|
OneToOneField,
|
|
50
51
|
Max,
|
|
51
52
|
Min,
|
|
@@ -98,6 +99,6 @@ from . import model
|
|
|
98
99
|
__all__ = [
|
|
99
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",
|
|
100
101
|
"IntegerField", "PositiveIntegerField", "BigIntField", "BigIntegerField", "PositiveBigIntegerField", "DecimalField", "StringField", "EmailField", "IPField", "PhoneField", "TextField", "UUIDField", "ImageField", "FileField", "FileImageField", "URLField", "BooleanField", "FloatField", "User",
|
|
101
|
-
"DateTimeField", "DateField", "TimeField", "DurationField", "JSONField", "ForeignKeyField", "OneToOneField", "ManyToManyField", "Count", "Sum", "Min", "Max", "Avg", "Request", "UploadFile", "Response", "JSONResponse",
|
|
102
|
+
"DateTimeField", "DateField", "TimeField", "DurationField", "JSONField", "ForeignKeyField", "OneToOneField", "OneToManyField", "ManyToManyField", "Count", "Sum", "Min", "Max", "Avg", "Request", "UploadFile", "Response", "JSONResponse",
|
|
102
103
|
"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",
|
|
103
104
|
]
|
|
@@ -14,7 +14,7 @@ from pathlib import Path
|
|
|
14
14
|
from typing import Any, get_args
|
|
15
15
|
|
|
16
16
|
from pydantic import BaseModel, TypeAdapter, ValidationError
|
|
17
|
-
from sqlalchemy.exc import IntegrityError, MultipleResultsFound
|
|
17
|
+
from sqlalchemy.exc import DBAPIError, IntegrityError, MultipleResultsFound, NoSuchTableError
|
|
18
18
|
from sqlalchemy.engine import make_url
|
|
19
19
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
20
20
|
|
|
@@ -50,6 +50,63 @@ from .sentinels import UNSET
|
|
|
50
50
|
logger = get_logger("websocket")
|
|
51
51
|
|
|
52
52
|
|
|
53
|
+
def _is_missing_table_error(exc: BaseException) -> bool:
|
|
54
|
+
"""Recognize common missing-table errors without exposing database details."""
|
|
55
|
+
current: BaseException | None = exc
|
|
56
|
+
seen: set[int] = set()
|
|
57
|
+
while current is not None and id(current) not in seen:
|
|
58
|
+
seen.add(id(current))
|
|
59
|
+
if isinstance(current, NoSuchTableError):
|
|
60
|
+
return True
|
|
61
|
+
if isinstance(current, DBAPIError):
|
|
62
|
+
original = current.orig
|
|
63
|
+
code = getattr(original, "sqlstate", None) or getattr(original, "pgcode", None)
|
|
64
|
+
args = getattr(original, "args", ())
|
|
65
|
+
if code == "42P01" or (args and args[0] == 1146):
|
|
66
|
+
return True
|
|
67
|
+
message = str(original).lower()
|
|
68
|
+
if any(marker in message for marker in (
|
|
69
|
+
"no such table", "undefined table", "doesn't exist", "does not exist",
|
|
70
|
+
)):
|
|
71
|
+
return True
|
|
72
|
+
current = current.__cause__ or current.__context__
|
|
73
|
+
return False
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _database_type_mismatch_detail(exc: BaseException) -> str | None:
|
|
77
|
+
"""Return a safe validation hint for PostgreSQL integer/string comparisons."""
|
|
78
|
+
current: BaseException | None = exc
|
|
79
|
+
seen: set[int] = set()
|
|
80
|
+
while current is not None and id(current) not in seen:
|
|
81
|
+
seen.add(id(current))
|
|
82
|
+
if isinstance(current, DBAPIError):
|
|
83
|
+
original = current.orig
|
|
84
|
+
code = getattr(original, "sqlstate", None) or getattr(original, "pgcode", None)
|
|
85
|
+
message = str(original).lower()
|
|
86
|
+
type_match = re.search(
|
|
87
|
+
r"(?:operator does not exist:\s*)?"
|
|
88
|
+
r"(smallint|integer|bigint|int2|int4|int8)\s*=\s*"
|
|
89
|
+
r"(character varying|varchar|text)",
|
|
90
|
+
message,
|
|
91
|
+
)
|
|
92
|
+
if code == "42883" or "no operator matches the given name and argument types" in message:
|
|
93
|
+
if type_match:
|
|
94
|
+
statement = current.statement or ""
|
|
95
|
+
field_match = re.search(
|
|
96
|
+
r"(?:\.|\")([A-Za-z_][A-Za-z0-9_]*)\"?\s*=\s*%\(",
|
|
97
|
+
statement,
|
|
98
|
+
)
|
|
99
|
+
field_name = field_match.group(1) if field_match else "value"
|
|
100
|
+
required_type = (
|
|
101
|
+
"int" if type_match.group(1) in {
|
|
102
|
+
"smallint", "integer", "bigint", "int2", "int4", "int8"
|
|
103
|
+
} else "number"
|
|
104
|
+
)
|
|
105
|
+
return f"{field_name} requires {required_type} but received string"
|
|
106
|
+
current = current.__cause__ or current.__context__
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
|
|
53
110
|
def _uses_basic_auth(endpoint: Callable, auth: Any) -> bool:
|
|
54
111
|
"""Detect BasicAuth supplied directly or through endpoint dependencies."""
|
|
55
112
|
from .security import BasicAuth
|
|
@@ -689,12 +746,32 @@ class Application(Router):
|
|
|
689
746
|
)
|
|
690
747
|
except DatabaseBackendMismatch as exc:
|
|
691
748
|
response = JSONResponse({"detail": str(exc)}, status_code=500)
|
|
692
|
-
except Exception:
|
|
693
|
-
if
|
|
694
|
-
logger.
|
|
749
|
+
except Exception as exc:
|
|
750
|
+
if _is_missing_table_error(exc):
|
|
751
|
+
logger.error(
|
|
752
|
+
"Model or table not found. Check model registration and apply pending migrations."
|
|
753
|
+
)
|
|
754
|
+
response = JSONResponse(
|
|
755
|
+
{
|
|
756
|
+
"detail": (
|
|
757
|
+
"Model or table not found. Check that the model is registered "
|
|
758
|
+
"and its migrations have been applied."
|
|
759
|
+
)
|
|
760
|
+
},
|
|
761
|
+
status_code=500,
|
|
762
|
+
)
|
|
763
|
+
elif type_detail := _database_type_mismatch_detail(exc):
|
|
764
|
+
logger.error(
|
|
765
|
+
"Invalid query value type: %s. Check the request value against the model field type.",
|
|
766
|
+
type_detail,
|
|
767
|
+
)
|
|
768
|
+
response = JSONResponse({"detail": type_detail}, status_code=422)
|
|
695
769
|
else:
|
|
696
|
-
|
|
697
|
-
|
|
770
|
+
if self.debug:
|
|
771
|
+
logger.exception("Unhandled application error for %s %s", method, path)
|
|
772
|
+
else:
|
|
773
|
+
logger.error("Unhandled application error for %s %s", method, path)
|
|
774
|
+
response = JSONResponse({"detail": "Internal Server Error"}, status_code=500)
|
|
698
775
|
finally:
|
|
699
776
|
reset_current_request(request_token)
|
|
700
777
|
reset_current_database_backend(database_backend_token)
|