lenapi 0.1.4.2__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.
Files changed (52) hide show
  1. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/PKG-INFO +50 -32
  2. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/README.md +49 -31
  3. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/__init__.py +3 -2
  4. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/application.py +83 -6
  5. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/authentication.py +62 -4
  6. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/cli.py +219 -2
  7. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/model.py +2 -1
  8. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/models.py +415 -20
  9. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/security.py +245 -28
  10. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi.egg-info/PKG-INFO +50 -32
  11. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/pyproject.toml +1 -1
  12. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/tests/test_framework_features.py +156 -0
  13. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/tests/test_user_model_extension.py +24 -0
  14. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/LICENSE +0 -0
  15. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/admin.py +0 -0
  16. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/auth.py +0 -0
  17. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/authorization.py +0 -0
  18. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/background.py +0 -0
  19. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/concurrency.py +0 -0
  20. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/database.py +0 -0
  21. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/dependencies.py +0 -0
  22. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/docs_guard.py +0 -0
  23. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/logging.py +0 -0
  24. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/middleware.py +0 -0
  25. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/mongodb.py +0 -0
  26. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/openapi.py +0 -0
  27. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/parameters.py +0 -0
  28. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/project.py +0 -0
  29. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/request.py +0 -0
  30. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/response.py +0 -0
  31. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/security_store.py +0 -0
  32. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/sentinels.py +0 -0
  33. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/service.py +0 -0
  34. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/throttling.py +0 -0
  35. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi/transaction.py +0 -0
  36. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi.egg-info/SOURCES.txt +0 -0
  37. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi.egg-info/dependency_links.txt +0 -0
  38. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi.egg-info/entry_points.txt +0 -0
  39. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi.egg-info/requires.txt +0 -0
  40. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi.egg-info/top_level.txt +0 -0
  41. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/lenapi_bootstrap.py +0 -0
  42. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/setup.cfg +0 -0
  43. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/tests/test_admin_console.py +0 -0
  44. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/tests/test_cli_settings_recovery.py +0 -0
  45. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/tests/test_docs_guard.py +0 -0
  46. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/tests/test_media_upload.py +0 -0
  47. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/tests/test_mongodb.py +0 -0
  48. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/tests/test_platform_services.py +0 -0
  49. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/tests/test_project_isolation.py +0 -0
  50. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/tests/test_security_patch.py +0 -0
  51. {lenapi-0.1.4.2 → lenapi-0.1.4.3}/tests/test_sentinels.py +0 -0
  52. {lenapi-0.1.4.2 → 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.2
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("classroom.id", nullable=True, model=model.null)
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
- 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`, and `ManyToManyField`. Fields normally default to `nullable=True` and `blank=True`; `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:
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
- For async code, use the stored foreign-key ID for a second async lookup. `.special()` is a sync helper:
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.aget(id=1)
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, eager-load the collection with SQLAlchemy's `selectinload` and the injected `AsyncSession` before reading it. Direct lazy access would try to perform database I/O during ordinary attribute access:
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
- from sqlalchemy import select
2154
- from sqlalchemy.ext.asyncio import AsyncSession
2155
- from sqlalchemy.orm import selectinload
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
- @app.get("/teachers/{teacher_id}/courses")
2160
- async def teacher_courses(teacher_id: int, db: AsyncSession):
2161
- result = await db.scalars(
2162
- select(Teacher)
2163
- .options(selectinload(Teacher.courses))
2164
- .where(Teacher.id == teacher_id)
2165
- )
2166
- teacher = result.one_or_none()
2167
- if teacher is None:
2168
- raise HTTPException(404, "Teacher not found")
2169
- return [{"id": course.id, "name": course.name}
2170
- for course in teacher.courses.all()]
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
- Declare the relationships in `app/models.py` and run `python lenora.py migration` before querying them. Async relationship loading requires `ACTIVATE_ASYNC = True` and the matching async driver.
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
 
@@ -2329,7 +2346,7 @@ classroom_name = student.classroom_id.name
2329
2346
 
2330
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`.
2331
2348
 
2332
- 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. A one-to-many relation uses an ordinary `ForeignKeyField` on the many-side; query matching rows with `filter()`:
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`:
2333
2350
 
2334
2351
  ```python
2335
2352
  class Classroom(model.Model):
@@ -2343,15 +2360,16 @@ class LearnerProfile(model.Model):
2343
2360
  learner_id = model.OneToOneField("learner.id", nullable=False)
2344
2361
  biography = model.TextField()
2345
2362
 
2346
- classroom = Classroom.get_or_404(id=1)
2347
- learners = Learner.filter(classroom_id=classroom.id).all()
2363
+ classrooms = Classroom.get(id=1).batch("learners").all()
2364
+ classroom = classrooms[0] if classrooms else None
2365
+ learners = classroom.learners if classroom else []
2348
2366
  learner = Learner.get_or_404(id=1).special("classroom_id")
2349
2367
  print(learner.classroom_id.name)
2350
2368
 
2351
2369
  profile = LearnerProfile.get(learner_id=learner.id).get()
2352
2370
  ```
2353
2371
 
2354
- For many-to-many queries, load the owning model and access its set-like collection. With async routes, await model query methods; use eager loading with SQLAlchemy `selectinload()` when traversing async relationships.
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")`.
2355
2373
 
2356
2374
  Choose what happens to dependent records when their referenced model is deleted with `model`:
2357
2375
 
@@ -2378,7 +2396,7 @@ teacher.courses.remove(course)
2378
2396
  teacher.save()
2379
2397
  ```
2380
2398
 
2381
- 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.
2382
2400
 
2383
2401
  ```python
2384
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("classroom.id", nullable=True, model=model.null)
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
- 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`, and `ManyToManyField`. Fields normally default to `nullable=True` and `blank=True`; `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:
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
- For async code, use the stored foreign-key ID for a second async lookup. `.special()` is a sync helper:
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.aget(id=1)
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, eager-load the collection with SQLAlchemy's `selectinload` and the injected `AsyncSession` before reading it. Direct lazy access would try to perform database I/O during ordinary attribute access:
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
- from sqlalchemy import select
2102
- from sqlalchemy.ext.asyncio import AsyncSession
2103
- from sqlalchemy.orm import selectinload
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
- @app.get("/teachers/{teacher_id}/courses")
2108
- async def teacher_courses(teacher_id: int, db: AsyncSession):
2109
- result = await db.scalars(
2110
- select(Teacher)
2111
- .options(selectinload(Teacher.courses))
2112
- .where(Teacher.id == teacher_id)
2113
- )
2114
- teacher = result.one_or_none()
2115
- if teacher is None:
2116
- raise HTTPException(404, "Teacher not found")
2117
- return [{"id": course.id, "name": course.name}
2118
- for course in teacher.courses.all()]
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
- Declare the relationships in `app/models.py` and run `python lenora.py migration` before querying them. Async relationship loading requires `ACTIVATE_ASYNC = True` and the matching async driver.
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
 
@@ -2277,7 +2294,7 @@ classroom_name = student.classroom_id.name
2277
2294
 
2278
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`.
2279
2296
 
2280
- 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. A one-to-many relation uses an ordinary `ForeignKeyField` on the many-side; query matching rows with `filter()`:
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`:
2281
2298
 
2282
2299
  ```python
2283
2300
  class Classroom(model.Model):
@@ -2291,15 +2308,16 @@ class LearnerProfile(model.Model):
2291
2308
  learner_id = model.OneToOneField("learner.id", nullable=False)
2292
2309
  biography = model.TextField()
2293
2310
 
2294
- classroom = Classroom.get_or_404(id=1)
2295
- learners = Learner.filter(classroom_id=classroom.id).all()
2311
+ classrooms = Classroom.get(id=1).batch("learners").all()
2312
+ classroom = classrooms[0] if classrooms else None
2313
+ learners = classroom.learners if classroom else []
2296
2314
  learner = Learner.get_or_404(id=1).special("classroom_id")
2297
2315
  print(learner.classroom_id.name)
2298
2316
 
2299
2317
  profile = LearnerProfile.get(learner_id=learner.id).get()
2300
2318
  ```
2301
2319
 
2302
- For many-to-many queries, load the owning model and access its set-like collection. With async routes, await model query methods; use eager loading with SQLAlchemy `selectinload()` when traversing async relationships.
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")`.
2303
2321
 
2304
2322
  Choose what happens to dependent records when their referenced model is deleted with `model`:
2305
2323
 
@@ -2326,7 +2344,7 @@ teacher.courses.remove(course)
2326
2344
  teacher.save()
2327
2345
  ```
2328
2346
 
2329
- 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.
2330
2348
 
2331
2349
  ```python
2332
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.2"
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 self.debug:
694
- logger.exception("Unhandled application error for %s %s", method, path)
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
- logger.error("Unhandled application error for %s %s", method, path)
697
- response = JSONResponse({"detail": "Internal Server Error"}, status_code=500)
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)
@@ -5,6 +5,8 @@ model, rather than putting credential lookup and password handling in
5
5
  ``main.py``.
6
6
  """
7
7
 
8
+ import asyncio
9
+
8
10
  from pydantic import BaseModel, ConfigDict, Field, model_validator
9
11
  from importlib import import_module
10
12
 
@@ -80,6 +82,31 @@ def _user_authenticator(user_model, identifier_field="username", password_field=
80
82
  return authenticate
81
83
 
82
84
 
85
+ def _async_user_authenticator(user_model, identifier_field="username", password_field="password"):
86
+ """Build an async SQL-backed credential check for a user model."""
87
+ columns = user_model.__table__.columns
88
+ if identifier_field not in columns:
89
+ raise ValueError(f"Authentication identifier '{identifier_field}' is not a field on {user_model.__name__}")
90
+ if password_field not in columns:
91
+ raise ValueError(f"Password field '{password_field}' is not a field on {user_model.__name__}")
92
+
93
+ async def authenticate(identifier, password):
94
+ user = await user_model.aget(**{identifier_field: identifier})
95
+ stored_password = (
96
+ getattr(user, password_field) if user is not None else _DUMMY_PASSWORD_HASH
97
+ )
98
+ # PBKDF2 is CPU-bound; move it off the event loop even though the
99
+ # database lookup itself is asynchronous.
100
+ password_matches = await asyncio.to_thread(
101
+ check_password, password, stored_password
102
+ )
103
+ if user is not None and password_matches:
104
+ return str(user.id)
105
+ return None
106
+
107
+ return authenticate
108
+
109
+
83
110
  def basic(user_model, *, identifier_field="username", password_field="password"):
84
111
  """Create database-backed HTTP Basic authentication for a user model."""
85
112
  return BasicAuth(_user_authenticator(user_model, identifier_field, password_field))
@@ -104,7 +131,7 @@ def api_key(user_model, *, field="api_key", header_name="x-api-key"):
104
131
 
105
132
 
106
133
  def jwt_auth(settings, user_model=None, *, identifier_field="username", password_field="password",
107
- security_store=None):
134
+ security_store=None, cache=None, allow_multiple_sessions=True):
108
135
  """Create JWT authentication, optionally backed by a project user model.
109
136
 
110
137
  Use ``auth.router(authenticate)`` to mount token and refresh endpoints.
@@ -116,18 +143,31 @@ def jwt_auth(settings, user_model=None, *, identifier_field="username", password
116
143
  refresh_token_lifetime_seconds=token.get("REFRESH_LIFETIME_SECONDS", 60 * 60 * 24 * 30),
117
144
  issuer=token.get("ISSUER"),
118
145
  security_store=security_store,
146
+ session_store=cache if cache is not None else security_store,
147
+ allow_multiple_sessions=allow_multiple_sessions,
119
148
  login_field=identifier_field,
120
149
  authenticate=(
121
150
  _user_authenticator(user_model, identifier_field, password_field)
122
151
  if user_model is not None else None
123
152
  ),
153
+ authenticate_async=(
154
+ _async_user_authenticator(user_model, identifier_field, password_field)
155
+ if user_model is not None else None
156
+ ),
124
157
  )
125
158
  return auth
126
159
 
127
160
 
128
- def session(*, store=None, lookup=None, cookie_name="lenapi_session"):
161
+ def session(
162
+ *, store=None, cache=None, lookup=None, cookie_name="lenapi_session",
163
+ allow_multiple_sessions=True,
164
+ ):
129
165
  """Create session authentication for use as a route dependency."""
130
- return SessionAuth(lookup, store=store if lookup is None else None, cookie_name=cookie_name)
166
+ return SessionAuth(
167
+ lookup, store=store if lookup is None and cache is None else None,
168
+ cache=cache if lookup is None else None, cookie_name=cookie_name,
169
+ allow_multiple_sessions=allow_multiple_sessions,
170
+ )
131
171
 
132
172
 
133
173
  def opaque_bearer(*, store=None, lookup=None):
@@ -158,8 +198,12 @@ def configure(
158
198
  api_key_field=None,
159
199
  identifier_field=None,
160
200
  password_field="password",
201
+ allow_multiple_sessions=None,
202
+ cache=None,
161
203
  ):
162
204
  """Build the primary authenticator selected by ``settings.AUTHENTICATION``."""
205
+ if allow_multiple_sessions is None:
206
+ allow_multiple_sessions = getattr(settings, "ALLOW_MULTIPLE_SESSIONS", True)
163
207
  if user_model is None:
164
208
  from .models import User
165
209
 
@@ -181,10 +225,18 @@ def configure(
181
225
  identifier_field=identifier_field,
182
226
  password_field=password_field,
183
227
  security_store=security_store,
228
+ cache=cache,
229
+ allow_multiple_sessions=allow_multiple_sessions,
184
230
  )
185
231
  if mode == "session":
186
232
  options = getattr(settings, "SESSION", {})
187
- return session(store=security_store, cookie_name=options.get("COOKIE_NAME", "lenapi_session"))
233
+ configured_policy = options.get("ALLOW_MULTIPLE_SESSIONS", allow_multiple_sessions)
234
+ return session(
235
+ store=security_store if cache is None else None,
236
+ cache=cache,
237
+ cookie_name=options.get("COOKIE_NAME", "lenapi_session"),
238
+ allow_multiple_sessions=configured_policy,
239
+ )
188
240
  if mode == "opaque_bearer":
189
241
  return opaque_bearer(store=security_store)
190
242
  if mode == "hmac":
@@ -208,6 +260,7 @@ def authentication_type(
208
260
  api_key_field=None,
209
261
  identifier_field=None,
210
262
  password_field="password",
263
+ allow_multiple_sessions=None,
211
264
  app=None,
212
265
  ):
213
266
  """Create the authenticator selected by a project settings module.
@@ -235,9 +288,11 @@ def authentication_type(
235
288
  selected_settings,
236
289
  user_model,
237
290
  security_store=getattr(app, "security_store", None),
291
+ cache=getattr(app, "cache", None),
238
292
  api_key_field=api_key_field,
239
293
  identifier_field=identifier_field,
240
294
  password_field=password_field,
295
+ allow_multiple_sessions=allow_multiple_sessions,
241
296
  )
242
297
  return authenticator
243
298
 
@@ -250,6 +305,7 @@ def authentication(
250
305
  api_key_field=None,
251
306
  identifier_field=None,
252
307
  password_field="password",
308
+ allow_multiple_sessions=None,
253
309
  app=None,
254
310
  ):
255
311
  """Create a route authentication dependency from project settings.
@@ -276,6 +332,7 @@ def authentication(
276
332
  api_key_field=api_key_field,
277
333
  identifier_field=identifier_field,
278
334
  password_field=password_field,
335
+ allow_multiple_sessions=allow_multiple_sessions,
279
336
  app=app,
280
337
  )
281
338
 
@@ -288,6 +345,7 @@ def install_default_authentication(app, settings):
288
345
  authenticator = authentication_type(
289
346
  mode, settings=settings, user_model=User,
290
347
  api_key_field="api_key" if mode == "api_key" else None,
348
+ allow_multiple_sessions=None,
291
349
  app=app,
292
350
  )
293
351