GREEN: Had to fiddle a bit with schemas and typing

This commit is contained in:
Colin Goutte 2023-08-27 20:06:25 +02:00
parent a7975cf164
commit 8ef89ecc85
3 changed files with 30 additions and 5 deletions

20
dev.py
View File

@ -118,8 +118,9 @@ async def list_movie(
db: Session = Depends(get_db),
pagenum: int | None = None,
pagesize: int | None = None,
) -> schemas.MovieObjectsOut:
) -> schemas.PaginatedMovies | schemas.MovieObjectsOut:
paginate_params = {}
paginate_data = {}
pagination_params = {"pagenum": pagenum, "pagesize": pagesize}
if any(v for v in pagination_params.values() if v is not None):
@ -127,13 +128,26 @@ async def list_movie(
if missing:
raise HTTPException(status_code=404, detail=f"Missing {missing}")
paginate_params = dict(offset=(pagenum - 1) * pagesize, limit=pagesize)
# Here we do a "x + 1 - 1 = x" trick to check if there will be more pages
# eg we want from 10 to 15, we ask for 10 to 16, if we have *stricly* more
# than 5 element we can now that there will be one more page
paginate_params = dict(offset=(pagenum - 1) * pagesize, limit=pagesize + 1)
movies = crud.get_all_movies(db, **paginate_params)
if paginate_params:
has_more_content = movies.count() > pagesize
paginate_data = {
"next_page": pagenum + 1 if has_more_content else None,
"previous_page": pagenum - 1 if pagenum > 1 else None,
}
movies = movies.limit(pagesize)
count = movies.count()
return {"movies": movies, "count": count}
payload = {"movies": movies, "count": count}
return {**payload, **paginate_data}
if __name__ == "__main__":

View File

@ -16,6 +16,15 @@ class MovieObject(MoviePayload):
id: int | str
class Paginated(BaseModel):
next_page: str | int | None
previous_page: str | int | None
class MovieObjectsOut(BaseModel):
movies: list[MovieObject]
count: int
class PaginatedMovies(MovieObjectsOut, Paginated):
pass

View File

@ -175,12 +175,14 @@ class BaseCrud(unittest.TestCase):
current_movies = client.get(
f"/movies/?pagenum={pagenum}&pagesize={pagesize}"
).json()
assert current_movies["previous_page"] is None
assert current_movies.get("previous_page") is None
assert current_movies["next_page"]
current_movies = client.get(
f"/movies/?pagenum={pagenum + 1 }&pagesize={pagesize}"
).json()
assert current_movies["next_page"] is None
assert current_movies.get("next_page") is None
assert current_movies["previous_page"]
# test last page has no next