Debian Codegraph @

docs/examples/pagination/using_offset_pagination.py

raw
1 import dataclasses
2 from itertools import islice
3 from typing import List
4
5 from polyfactory.factories.dataclass_factory import DataclassFactory
6
7 from litestar import Litestar, get
8 from litestar.pagination import AbstractSyncOffsetPaginator, OffsetPagination
9 from litestar.params import FromQuery
10
11
12 @dataclasses.dataclass
13 class Person:
14 id: str
15 name: str
16
17
18 class PersonFactory(DataclassFactory[Person]):
19 __model__ = Person
20
21
22 # we will implement a paginator - the paginator must implement two methods 'get_total' and 'get_items'
23 # we would usually use a database for this, but for our case we will "fake" the dataset using a factory.
24
25
26 class PersonOffsetPaginator(AbstractSyncOffsetPaginator[Person]):
27 def __init__(self) -> None:
28 self.data = PersonFactory.batch(50)
29
30 def get_total(self) -> int:
31 return len(self.data)
32
33 def get_items(self, limit: int, offset: int) -> List[Person]:
34 return list(islice(islice(self.data, offset, None), limit))
35
36
37 paginator = PersonOffsetPaginator()
38
39
40 # we now create a regular handler. The handler will receive two query parameters - 'limit' and 'offset', which
41 # we will pass to the paginator.
42 @get("/people", sync_to_thread=False)
43 def people_handler(limit: FromQuery[int], offset: FromQuery[int]) -> OffsetPagination[Person]:
44 return paginator(limit=limit, offset=offset)
45
46
47 app = Litestar(route_handlers=[people_handler])