fastapi-sqlalchemy-toolkit 0.6.8__tar.gz → 0.6.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.
Files changed (28) hide show
  1. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/PKG-INFO +1 -1
  2. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/examples/app/api/endpoints/child.py +0 -2
  3. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/examples/app/main.py +3 -0
  4. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/fastapi_sqlalchemy_toolkit/model_manager.py +34 -40
  5. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/pyproject.toml +1 -1
  6. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/.flake8 +0 -0
  7. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/.github/workflows/python-publish.yml +0 -0
  8. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/.gitignore +0 -0
  9. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/.pylintrc +0 -0
  10. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/AUTHORS +0 -0
  11. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/LICENSE +0 -0
  12. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/README.md +0 -0
  13. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/examples/app/.env +0 -0
  14. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/examples/app/__init__.py +0 -0
  15. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/examples/app/api/__init__.py +0 -0
  16. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/examples/app/api/api.py +0 -0
  17. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/examples/app/api/endpoints/__init__.py +0 -0
  18. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/examples/app/config.py +0 -0
  19. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/examples/app/db.py +0 -0
  20. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/examples/app/deps.py +0 -0
  21. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/examples/app/managers.py +0 -0
  22. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/examples/app/models.py +0 -0
  23. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/examples/app/schemas.py +0 -0
  24. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/fastapi_sqlalchemy_toolkit/__init__.py +0 -0
  25. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/fastapi_sqlalchemy_toolkit/filters.py +0 -0
  26. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/fastapi_sqlalchemy_toolkit/ordering.py +0 -0
  27. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/fastapi_sqlalchemy_toolkit/utils.py +0 -0
  28. {fastapi_sqlalchemy_toolkit-0.6.8 → fastapi_sqlalchemy_toolkit-0.6.9}/requirements.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fastapi_sqlalchemy_toolkit
3
- Version: 0.6.8
3
+ Version: 0.6.9
4
4
  Summary: FastAPI SQLAlchemy Toolkit
5
5
  Project-URL: Homepage, https://github.com/e-kondr01/fastapi-sqlalchemy-toolkit
6
6
  Author-email: Egor Kondrashov <e.kondr01@gmail.com>
@@ -32,7 +32,6 @@ children_ordering_fields = (Parent.created_at, Parent.title, "created_at", "titl
32
32
  async def get_list(
33
33
  session: Session,
34
34
  order_by: ordering_dep(children_ordering_fields),
35
- pagination_params: PaginationParams,
36
35
  title: str | None = None,
37
36
  slug: str | None = None,
38
37
  parent_title: str | None = None,
@@ -42,7 +41,6 @@ async def get_list(
42
41
  return await child_manager.paginated_list(
43
42
  # Обязательные параметры
44
43
  session,
45
- pagination_params,
46
44
  # Фильтры
47
45
  slug=slug,
48
46
  filter_expressions={
@@ -1,5 +1,6 @@
1
1
  from fastapi import FastAPI
2
2
  from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi_pagination import add_pagination
3
4
 
4
5
  from .api.api import api_router
5
6
 
@@ -18,4 +19,6 @@ app.add_middleware(
18
19
  allow_headers=["*"],
19
20
  )
20
21
 
22
+ add_pagination(app)
23
+
21
24
  app.include_router(api_router, prefix="/api")
@@ -1,7 +1,7 @@
1
1
  from typing import Any, Callable, Generic, Iterable, List, Type, TypeVar
2
2
 
3
3
  from fastapi import HTTPException, status
4
- from fastapi_pagination.bases import AbstractParams, BasePage
4
+ from fastapi_pagination.bases import BasePage
5
5
  from fastapi_pagination.ext.sqlalchemy import paginate
6
6
  from pydantic import BaseModel
7
7
  from sqlalchemy import Row, UniqueConstraint, func, select
@@ -17,22 +17,22 @@ from sqlalchemy.sql.selectable import Exists
17
17
  from .filters import null_query_values
18
18
  from .ordering import OrderingField
19
19
 
20
- ModelType = TypeVar("ModelType", bound=DeclarativeBase)
21
- CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
22
- UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
20
+ ModelT = TypeVar("ModelT", bound=DeclarativeBase)
21
+ CreateSchemaT = TypeVar("CreateSchemaT", bound=BaseModel)
22
+ UpdateSchemaT = TypeVar("UpdateSchemaT", bound=BaseModel)
23
23
  ModelDict = dict[str, Any]
24
24
 
25
25
 
26
- def sqlalchemy_model_to_dict(model: ModelType) -> dict:
26
+ def sqlalchemy_model_to_dict(model: ModelT) -> dict:
27
27
  db_obj_dict = model.__dict__.copy()
28
28
  del db_obj_dict["_sa_instance_state"]
29
29
  return db_obj_dict
30
30
 
31
31
 
32
- class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
32
+ class ModelManager(Generic[ModelT, CreateSchemaT, UpdateSchemaT]):
33
33
  def __init__(
34
34
  self,
35
- model: Type[ModelType],
35
+ model: Type[ModelT],
36
36
  default_ordering: InstrumentedAttribute | UnaryExpression | None = None,
37
37
  ) -> None:
38
38
  """
@@ -49,7 +49,7 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
49
49
  # str() of FK attr to related model
50
50
  # "parent_id": <class app.models.parent.Parent>
51
51
  # Используется для валидации существования FK при создании/обновлении объекта
52
- self.fk_name_to_model: dict[str, Type[ModelType]] = {}
52
+ self.fk_name_to_model: dict[str, Type[ModelT]] = {}
53
53
 
54
54
  self.unique_constraints: List[List[str]] = []
55
55
  if hasattr(self.model, "__table_args__"):
@@ -60,13 +60,13 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
60
60
  else:
61
61
  self.unique_constraints.append(table_arg._pending_colargs)
62
62
 
63
- self.reverse_relationships: dict[str, Type[ModelType]] = {}
64
- self.m2m_relationships: dict[str, Type[ModelType]] = {}
63
+ self.reverse_relationships: dict[str, Type[ModelT]] = {}
64
+ self.m2m_relationships: dict[str, Type[ModelT]] = {}
65
65
  # Model to related attr
66
66
  # Parent : Child.parent
67
67
  # Используется при составлении join'ов для фильтрации и сортировки
68
68
  self.models_to_relationship_attrs: dict[
69
- Type[ModelType], InstrumentedAttribute
69
+ Type[ModelT], InstrumentedAttribute
70
70
  ] = {}
71
71
 
72
72
  attr: InstrumentedAttribute
@@ -95,11 +95,11 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
95
95
  async def create(
96
96
  self,
97
97
  session: AsyncSession,
98
- in_obj: CreateSchemaType | None = None,
98
+ in_obj: CreateSchemaT | None = None,
99
99
  refresh_attribute_names: Iterable[str] | None = None,
100
100
  commit: bool = True,
101
101
  **attrs: Any,
102
- ) -> ModelType:
102
+ ) -> ModelT:
103
103
  """
104
104
  Создание экземпляра модели и сохранение в БД.
105
105
  Также выполняет валидацию на уровне БД.
@@ -141,7 +141,7 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
141
141
  where: Any | None = None,
142
142
  select_: Select | None = None,
143
143
  **simple_filters: Any,
144
- ) -> ModelType | Row | None:
144
+ ) -> ModelT | Row | None:
145
145
  """
146
146
  Получение одного экземпляра модели при существовании
147
147
 
@@ -154,7 +154,7 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
154
154
  :param where: выражение, которое будет передано в метод .where() SQLAlchemy
155
155
 
156
156
  :param select_: объект Select для SQL запроса. Если передан, то метод вернёт
157
- экземпляр Row, а не ModelType.
157
+ экземпляр Row, а не ModelT.
158
158
  Примечание: фильтрация и сортировка по связанным моделям скорее всего
159
159
  не будут работать вместе с этим параметром.
160
160
 
@@ -178,7 +178,7 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
178
178
  where: Any | None = None,
179
179
  select_: Select | None = None,
180
180
  **simple_filters: Any,
181
- ) -> ModelType | Row:
181
+ ) -> ModelT | Row:
182
182
  """
183
183
  Получение одного экземпляра модели или вызов HTTP исключения 404.
184
184
 
@@ -191,7 +191,7 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
191
191
  :param where: выражение, которое будет передано в метод .where() SQLAlchemy
192
192
 
193
193
  :param select_: объект Select для SQL запроса. Если передан, то метод вернёт
194
- экземпляр Row, а не ModelType.
194
+ экземпляр Row, а не ModelT.
195
195
 
196
196
  :param simple_filters: параметры для фильтрации по точному соответствию,
197
197
  аналогично методу .filter_by() SQLAlchemy
@@ -294,20 +294,17 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
294
294
  async def paginated_filter(
295
295
  self,
296
296
  session: AsyncSession,
297
- pagination_params: AbstractParams,
298
297
  order_by: OrderingField | None = None,
299
298
  options: List[Any] | Any | None = None,
300
299
  where: Any | None = None,
301
300
  select_: Select | None = None,
302
301
  **simple_filters: Any,
303
- ) -> BasePage[ModelType | Row]:
302
+ ) -> BasePage[ModelT | Row]:
304
303
  """
305
304
  Получение списка объектов с фильтрами и пагинацией.
306
305
 
307
306
  :param session: сессия SQLAlchemy
308
307
 
309
- :pagination_params: параметры пагинации из fastapi_pagination
310
-
311
308
  :param order_by: поле для сортировки (экземпляр OrderingField)
312
309
 
313
310
  :param options: параметры для метода .options() загрузчика SQLAlchemy
@@ -315,7 +312,7 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
315
312
  :param where: выражение, которое будет передано в метод .where() SQLAlchemy
316
313
 
317
314
  :param select_: объект Select для SQL запроса. Если передан, то метод вернёт
318
- страницу Row, а не ModelType.
315
+ страницу Row, а не ModelT.
319
316
 
320
317
  :param simple_filters: параметры для фильтрации по точному соответствию,
321
318
  аналогично методу .filter_by() SQLAlchemy
@@ -323,12 +320,11 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
323
320
  :returns: пагинированный список объектов или Row
324
321
  """
325
322
  stmt = self.assemble_stmt(select_, order_by, options, where, **simple_filters)
326
- return await paginate(session, stmt, pagination_params)
323
+ return await paginate(session, stmt)
327
324
 
328
325
  async def paginated_list(
329
326
  self,
330
327
  session: AsyncSession,
331
- pagination_params: AbstractParams,
332
328
  order_by: OrderingField | None = None,
333
329
  filter_expressions: dict[InstrumentedAttribute | Callable, Any] | None = None,
334
330
  nullable_filter_expressions: dict[InstrumentedAttribute | Callable, Any]
@@ -337,15 +333,13 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
337
333
  where: Any | None = None,
338
334
  select_: Select | None = None,
339
335
  **simple_filters: Any,
340
- ) -> BasePage[ModelType | Row]:
336
+ ) -> BasePage[ModelT | Row]:
341
337
  """
342
338
  Получение списка объектов с фильтрами и пагинацией.
343
339
  Пропускает фильтры, значения которых None.
344
340
 
345
341
  :param session: сессия SQLAlchemy
346
342
 
347
- :pagination_params: параметры пагинации из fastapi_pagination
348
-
349
343
  :param order_by: поле для сортировки (экземпляр OrderingField)
350
344
 
351
345
  :param filter_expressions: словарь, отображающий поля для фильтрации
@@ -362,7 +356,7 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
362
356
  :param where: выражение, которое будет передано в метод .where() SQLAlchemy
363
357
 
364
358
  :param select_: объект Select для SQL запроса. Если передан, то метод вернёт
365
- страницу Row, а не ModelType.
359
+ страницу Row, а не ModelT.
366
360
  Примечание: фильтрация и сортировка по связанным моделям скорее всего
367
361
  не будет работать вместе с этим параметром.
368
362
 
@@ -396,7 +390,7 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
396
390
  else:
397
391
  stmt = stmt.filter(filter_expression(value))
398
392
 
399
- return await paginate(session, stmt, pagination_params)
393
+ return await paginate(session, stmt)
400
394
 
401
395
  async def filter(
402
396
  self,
@@ -407,7 +401,7 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
407
401
  unique: bool = False,
408
402
  select_: Select | None = None,
409
403
  **simple_filters: Any,
410
- ) -> List[ModelType] | List[Row]:
404
+ ) -> List[ModelT] | List[Row]:
411
405
  """
412
406
  Получение списка объектов с фильтрами
413
407
 
@@ -423,7 +417,7 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
423
417
  у результата SQLAlchemy
424
418
 
425
419
  :param select_: объект Select для SQL запроса. Если передан, то метод вернёт
426
- список Row, а не ModelType.
420
+ список Row, а не ModelT.
427
421
 
428
422
  :param simple_filters: параметры для фильтрации по точному соответствию,
429
423
  аналогично методу .filter_by() SQLAlchemy
@@ -451,7 +445,7 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
451
445
  unique: bool = False,
452
446
  select_: Select | None = None,
453
447
  **simple_filters: Any,
454
- ) -> List[ModelType] | List[Row]:
448
+ ) -> List[ModelT] | List[Row]:
455
449
  """
456
450
  Получение списка объектов с фильтрами.
457
451
  Пропускает фильтры, значения которых None.
@@ -477,7 +471,7 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
477
471
  у результата SQLAlchemy
478
472
 
479
473
  :param select_: объект Select для SQL запроса. Если передан, то метод вернёт
480
- список Row, а не ModelType.
474
+ список Row, а не ModelT.
481
475
  Примечание: фильтрация и сортировка по связанным моделям скорее всего
482
476
  не будут работать вместе с этим параметром.
483
477
 
@@ -554,13 +548,13 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
554
548
  async def update(
555
549
  self,
556
550
  session: AsyncSession,
557
- db_obj: ModelType,
558
- in_obj: UpdateSchemaType | None = None,
551
+ db_obj: ModelT,
552
+ in_obj: UpdateSchemaT | None = None,
559
553
  refresh_attribute_names: Iterable[str] | None = None,
560
554
  commit: bool = True,
561
555
  exclude_unset: bool = True,
562
556
  **attrs: Any,
563
- ) -> ModelType:
557
+ ) -> ModelT:
564
558
  """
565
559
  Обновление экземпляра модели в БД.
566
560
  Также выполняет валидацию на уровне БД.
@@ -604,8 +598,8 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
604
598
  return db_obj
605
599
 
606
600
  async def delete(
607
- self, session: AsyncSession, db_obj: ModelType, commit: bool = True
608
- ) -> ModelType | None:
601
+ self, session: AsyncSession, db_obj: ModelT, commit: bool = True
602
+ ) -> ModelT | None:
609
603
  """
610
604
  Удаление экземпляра модели из БД.
611
605
 
@@ -628,7 +622,7 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
628
622
  self,
629
623
  session: AsyncSession,
630
624
  in_obj: ModelDict,
631
- db_obj: ModelType | None = None,
625
+ db_obj: ModelT | None = None,
632
626
  ) -> ModelDict:
633
627
  """
634
628
  Выполнить валидацию на соответствие ограничениям БД.
@@ -849,7 +843,7 @@ class ModelManager(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
849
843
  self,
850
844
  session: AsyncSession,
851
845
  in_obj: ModelDict,
852
- db_obj: ModelType | None = None,
846
+ db_obj: ModelT | None = None,
853
847
  ) -> None:
854
848
  """
855
849
  Проверить соблюдение уникальности полей.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "fastapi_sqlalchemy_toolkit"
7
- version = "0.6.8"
7
+ version = "0.6.9"
8
8
  authors = [
9
9
  { name="Egor Kondrashov", email="e.kondr01@gmail.com" },
10
10
  ]