Files
mtusi2026lab2/app/pagination.py
T

44 lines
1.7 KiB
Python

import base64
import json
import re
from typing import Mapping, Optional, Tuple
from .errors import invalid_request
# Position of the last item returned to the client.
Key = Tuple[str, str]
DEFAULT_LIMIT = 50
MAX_LIMIT = 100
_LIMIT = re.compile(r'^\d{1,3}$')
def encode_cursor(scope: str, key: Key) -> str:
"""Scope binds the cursor to one resource, so a foreign cursor is detectable."""
payload = json.dumps({'s': scope, 't': key[0], 'i': key[1]}, separators=(',', ':'))
return base64.urlsafe_b64encode(payload.encode('utf-8')).decode('ascii').rstrip('=')
def decode_cursor(value: str, scope: str) -> Key:
try:
raw = base64.urlsafe_b64decode(value + '=' * (-len(value) % 4))
payload = json.loads(raw)
created_at, item_id = payload['t'], payload['i']
belongs = payload['s'] == scope
except (ValueError, TypeError, KeyError):
raise invalid_request('Некорректный cursor') from None
if not belongs or not isinstance(created_at, str) or not isinstance(item_id, str):
raise invalid_request('Cursor относится к другому запросу') from None
return created_at, item_id
def parse_page(params: Mapping[str, str], scope: str) -> Tuple[int, Optional[Key]]:
raw_limit = params.get('limit')
limit = DEFAULT_LIMIT
if raw_limit is not None:
if not _LIMIT.match(raw_limit) or not 1 <= int(raw_limit) <= MAX_LIMIT:
raise invalid_request('limit должен быть целым числом от 1 до %d' % MAX_LIMIT)
limit = int(raw_limit)
raw_cursor = params.get('cursor')
return limit, decode_cursor(raw_cursor, scope) if raw_cursor is not None else None