Spaces:
Running on T4
Running on T4
Download backend/app/core/pagination.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 1.76 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/core/pagination.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/backend/app/core/pagination.py
-
curl -L -o pagination.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/core/pagination.py
1.76 kB
| """Cursor pagination for lists ordered by (created_at, id).""" | |
| import base64 | |
| import json | |
| from collections.abc import Callable, Sequence | |
| from dataclasses import dataclass | |
| from datetime import datetime | |
| from typing import TypeVar | |
| from uuid import UUID | |
| from fastapi import Query | |
| from app.core.errors import ValidationFailed | |
| class Cursor: | |
| created_at: datetime | |
| id: UUID | |
| def encode_cursor(created_at: datetime, id_: UUID) -> str: | |
| raw = json.dumps({"created_at": created_at.isoformat(), "id": str(id_)}) | |
| return base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=") | |
| def decode_cursor(value: str) -> Cursor: | |
| try: | |
| padded = value + "=" * (-len(value) % 4) | |
| data = json.loads(base64.urlsafe_b64decode(padded)) | |
| return Cursor(datetime.fromisoformat(data["created_at"]), UUID(data["id"])) | |
| except (ValueError, KeyError, TypeError) as exc: | |
| raise ValidationFailed(fields={"cursor": "Invalid cursor."}) from exc | |
| T = TypeVar("T") | |
| def paginate(rows: Sequence[T], limit: int, key: Callable[[T], tuple[datetime, UUID]] | None = None | |
| ) -> tuple[list[T], str | None]: | |
| """Split rows fetched with limit + 1 into the page and its next cursor. key gives (created_at, id).""" | |
| page = list(rows[:limit]) | |
| if len(rows) <= limit: | |
| return page, None | |
| return page, encode_cursor(*(key(page[-1]) if key else (page[-1].created_at, page[-1].id))) # type: ignore[attr-defined] | |
| class PageParams: | |
| limit: int | |
| cursor: Cursor | None | |
| def page_params( | |
| limit: int = Query(50, ge=1, le=200), | |
| cursor: str | None = Query(None), | |
| ) -> PageParams: | |
| return PageParams(limit=limit, cursor=decode_cursor(cursor) if cursor else None) | |