Added fastapi pagination

This commit is contained in:
2024-04-01 18:16:11 +02:00
parent a004dd233a
commit 58dc5eb6f2
5 changed files with 88 additions and 0 deletions

View File

@@ -1,2 +1,9 @@
# creyPY
My collection of Python and FastAPI shortcuts etc.
# Release
``` rm -rf dist build creyPY.egg-info && python setup.py sdist bdist_wheel ```
``` twine upload dist/* ```

View File

@@ -1,2 +1,3 @@
from .groups import * # noqa
from .i18n import * # noqa
from .stripe import * # noqa

View File

@@ -0,0 +1 @@
from .pagination import * # noqa

View File

@@ -0,0 +1,69 @@
from math import ceil
from typing import Any, Generic, Optional, Self, Sequence, TypeVar
from fastapi_pagination import Params
from fastapi_pagination.bases import AbstractPage, AbstractParams
from fastapi_pagination.types import GreaterEqualOne, GreaterEqualZero
from pydantic.json_schema import SkipJsonSchema
T = TypeVar("T")
class Page(AbstractPage[T], Generic[T]):
results: Sequence[T]
page: GreaterEqualOne | SkipJsonSchema[None] = None
size: GreaterEqualOne | SkipJsonSchema[None] = None
pages: GreaterEqualZero | SkipJsonSchema[None] = None
total: GreaterEqualZero
has_next: bool | SkipJsonSchema[None] = None
has_prev: bool | SkipJsonSchema[None] = None
__params_type__ = Params
@classmethod
def create(
cls,
items: Sequence[T],
params: AbstractParams,
*,
total: Optional[int] = None,
**kwargs: Any,
) -> Self:
if not isinstance(params, Params):
raise TypeError("Page should be used with Params")
size = params.size or total or len(items)
page = params.page or 1
pages = None
if total is not None:
if total == 0:
pages = 1
else:
pages = ceil(total / size)
has_next = page < (pages or 1)
has_prev = page > 1
return cls(
total=total,
results=items,
page=page,
size=size,
pages=pages,
has_next=has_next,
has_prev=has_prev,
)
# Parse response from an SDK to a PAGE
def parse_page(response, page: int, size: int) -> Page:
return Page(
page=page,
size=size,
total=response.total,
results=response.results,
pages=response.pages or 1,
has_next=response.has_next,
has_prev=response.has_prev,
)

10
requirements.txt Normal file
View File

@@ -0,0 +1,10 @@
annotated-types==0.6.0 # Pydantic
pydantic==2.6.4 # Pydantic
pydantic-core==2.16.3 # Pydantic
typing-extensions==4.10.0 # Pydantic
anyio==4.3.0 # Pagination
fastapi==0.110.0 # Pagination
fastapi-pagination==0.12.21 # Pagination
sniffio==1.3.1 # Pagination
starlette==0.36.3 # Pagination