forked from mtusi2026/mtusi2026lab2
ЛР2: PostgreSQL, сессии (Basic + Bearer), Compose, миграции
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from utils.dates import format_utc, parse_utc
|
||||
|
||||
# Позиция в списке: (created_at, id) последнего выданного элемента.
|
||||
Position = tuple[datetime, uuid.UUID]
|
||||
|
||||
|
||||
def make_cursor(scope: str, created_at: datetime, item_id: uuid.UUID) -> str:
|
||||
data = json.dumps({"scope": scope, "created_at": format_utc(created_at), "id": str(item_id)})
|
||||
return base64.urlsafe_b64encode(data.encode()).decode()
|
||||
|
||||
|
||||
def read_cursor(scope: str, cursor: str | None) -> Position | None:
|
||||
if cursor is None:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor.encode()))
|
||||
if data["scope"] != scope:
|
||||
raise ValueError("cursor from another resource")
|
||||
return parse_utc(data["created_at"]), uuid.UUID(data["id"])
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="Неверный cursor")
|
||||
|
||||
|
||||
def split_page(rows: list, limit: int, scope: str) -> tuple[list, str | None]:
|
||||
"""rows получены с LIMIT limit + 1: лишняя строка значит, что есть следующая страница."""
|
||||
page = rows[:limit]
|
||||
next_cursor = make_cursor(scope, page[-1].created_at, page[-1].id) if len(rows) > limit else None
|
||||
return page, next_cursor
|
||||
Reference in New Issue
Block a user