Debian Codegraph @

docs/examples/pagination/using_offset_pagination_with_sqlalchemy.py

raw
1 from typing import TYPE_CHECKING, List, cast
2
3 from sqlalchemy import func, select
4 from sqlalchemy.orm import Mapped
5
6 from litestar import Litestar, get
7 from litestar.di import Provide
8 from litestar.pagination import AbstractAsyncOffsetPaginator, OffsetPagination
9 from litestar.params import FromQuery
10 from litestar.plugins.sqlalchemy import SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin, base
11
12 if TYPE_CHECKING:
13 from sqlalchemy.engine.result import ScalarResult
14 from sqlalchemy.ext.asyncio import AsyncSession
15
16
17 class Person(base.UUIDBase):
18 name: Mapped[str]
19
20
21 class PersonOffsetPaginator(AbstractAsyncOffsetPaginator[Person]):
22 def __init__(self, async_session: AsyncSession) -> None: # 'async_session' dependency will be injected here.
23 self.async_session = async_session
24
25 async def get_total(self) -> int:
26 return cast("int", await self.async_session.scalar(select(func.count(Person.id))))
27
28 async def get_items(self, limit: int, offset: int) -> List[Person]:
29 people: ScalarResult = await self.async_session.scalars(select(Person).slice(offset, limit))
30 return list(people.all())
31
32
33 # Create a route handler. The handler will receive two query parameters - 'limit' and 'offset', which is passed
34 # to the paginator instance. Also create a dependency 'paginator' which will be injected into the handler.
35 @get("/people", dependencies={"paginator": Provide(PersonOffsetPaginator)})
36 async def people_handler(
37 paginator: PersonOffsetPaginator, limit: FromQuery[int], offset: FromQuery[int]
38 ) -> OffsetPagination[Person]:
39 return await paginator(limit=limit, offset=offset)
40
41
42 sqlalchemy_config = SQLAlchemyAsyncConfig(
43 connection_string="sqlite+aiosqlite:///test.sqlite", session_dependency_key="async_session"
44 ) # Create 'async_session' dependency.
45 sqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config)
46
47
48 async def on_startup() -> None:
49 """Initializes the database."""
50 async with sqlalchemy_config.get_engine().begin() as conn:
51 await conn.run_sync(base.UUIDBase.metadata.create_all)
52
53
54 app = Litestar(route_handlers=[people_handler], on_startup=[on_startup], plugins=[sqlalchemy_plugin])