Debian Codegraph @

docs/examples/pagination/using_classic_pagination.py

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