diff --git a/unwind/db.py b/unwind/db.py index b81c482..9fa770e 100644 --- a/unwind/db.py +++ b/unwind/db.py @@ -2,7 +2,7 @@ import logging import re from dataclasses import fields from pathlib import Path -from typing import Literal, Optional, Type, TypeVar +from typing import Literal, Optional, Type, TypeVar, Union import sqlalchemy from databases import Database @@ -156,9 +156,9 @@ async def find_ratings( ignore_tv_episodes: bool = False, include_unrated: bool = False, yearcomp: tuple[Literal["<", "=", ">"], int] = None, - limit_rows=10, + limit_rows: int = 10, ): - values = { + values: dict[str, Union[int, str]] = { "limit_rows": limit_rows, } diff --git a/unwind/web.py b/unwind/web.py index 23d8128..411c519 100644 --- a/unwind/web.py +++ b/unwind/web.py @@ -1,7 +1,7 @@ import base64 import binascii import logging -from typing import Literal +from typing import Literal, Optional from starlette.applications import Starlette from starlette.authentication import ( @@ -63,6 +63,23 @@ def yearcomp(s: str): return comp, int(s) +def as_int(x, *, max: int = None, min: Optional[int] = 1, default: int = None): + try: + if not isinstance(x, int): + x = int(x) + if min is not None and x < min: + return min + if max is not None and x > max: + return max + return x + + except: + if default is None: + raise + + return default + + async def ratings(request): params = request.query_params rows = await find_ratings( @@ -71,6 +88,7 @@ async def ratings(request): ignore_tv_episodes=truthy(params.get("ignore_tv_episodes")), include_unrated=truthy(params.get("include_unrated")), yearcomp=yearcomp(params["year"]) if "year" in params else None, + limit_rows=as_int(params.get("per_page"), max=10, default=5), ) aggr = {}