|
| 1 | +from typing import TypeVar |
| 2 | + |
| 3 | +from fastapi import FastAPI |
| 4 | +from pydantic import BaseModel |
| 5 | +from sqlalchemy import create_engine, select |
| 6 | +from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column |
| 7 | + |
| 8 | +from fastapi_pagination import add_pagination |
| 9 | +from fastapi_pagination.cursor import CursorPage |
| 10 | +from fastapi_pagination.customization import CustomizedPage, UseIncludeTotal |
| 11 | +from fastapi_pagination.ext.sqlalchemy import paginate |
| 12 | + |
| 13 | +app = FastAPI() |
| 14 | +add_pagination(app) |
| 15 | + |
| 16 | +engine = create_engine("sqlite:///.db") |
| 17 | + |
| 18 | + |
| 19 | +class Base(DeclarativeBase): |
| 20 | + pass |
| 21 | + |
| 22 | + |
| 23 | +class User(Base): |
| 24 | + __tablename__ = "users" |
| 25 | + |
| 26 | + id: Mapped[int] = mapped_column(primary_key=True) |
| 27 | + |
| 28 | + name: Mapped[str] = mapped_column() |
| 29 | + age: Mapped[int] = mapped_column() |
| 30 | + |
| 31 | + |
| 32 | +class UserOut(BaseModel): |
| 33 | + id: int |
| 34 | + name: str |
| 35 | + age: int |
| 36 | + |
| 37 | + class Config: |
| 38 | + orm_mode = True |
| 39 | + |
| 40 | + |
| 41 | +@app.on_event("startup") |
| 42 | +def on_startup(): |
| 43 | + with engine.begin() as conn: |
| 44 | + Base.metadata.drop_all(conn) |
| 45 | + Base.metadata.create_all(conn) |
| 46 | + |
| 47 | + with Session(engine) as session: |
| 48 | + session.add_all( |
| 49 | + [ |
| 50 | + User(name="John", age=25), |
| 51 | + User(name="Jane", age=30), |
| 52 | + User(name="Bob", age=20), |
| 53 | + ], |
| 54 | + ) |
| 55 | + session.commit() |
| 56 | + |
| 57 | + |
| 58 | +T = TypeVar("T") |
| 59 | + |
| 60 | +CursorWithTotalPage = CustomizedPage[ |
| 61 | + CursorPage[T], |
| 62 | + UseIncludeTotal(True), |
| 63 | +] |
| 64 | + |
| 65 | + |
| 66 | +@app.get("/users") |
| 67 | +def get_users() -> CursorWithTotalPage[UserOut]: |
| 68 | + with Session(engine) as session: |
| 69 | + return paginate(session, select(User).order_by(User.id)) |
0 commit comments