ЛР 2: PostgreSQL, сессии и Valkey — на 4
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from src.errors import ApiError
|
||||
|
||||
|
||||
def encode_cursor(
|
||||
resource: str,
|
||||
owner_id: str,
|
||||
created_at: str,
|
||||
object_id: str,
|
||||
) -> str:
|
||||
payload = {
|
||||
"resource": resource,
|
||||
"owner_id": owner_id,
|
||||
"created_at": created_at,
|
||||
"id": object_id,
|
||||
}
|
||||
|
||||
raw = json.dumps(
|
||||
payload,
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(
|
||||
cursor: str,
|
||||
expected_resource: str,
|
||||
expected_owner_id: str,
|
||||
) -> tuple[str, str]:
|
||||
try:
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]+", cursor):
|
||||
raise ValueError
|
||||
padding = "=" * (-len(cursor) % 4)
|
||||
|
||||
raw = base64.b64decode(
|
||||
(cursor + padding).encode("ascii"), altchars=b"-_", validate=True
|
||||
)
|
||||
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
|
||||
if payload["resource"] != expected_resource:
|
||||
raise ValueError
|
||||
|
||||
if payload["owner_id"] != expected_owner_id:
|
||||
raise ValueError
|
||||
|
||||
created_at = payload["created_at"]
|
||||
object_id = payload["id"]
|
||||
|
||||
# The cursor must carry the same UTC timestamp format produced
|
||||
# by the server. Invalid timestamps must return HTTP 400 before a SQL cast.
|
||||
if not isinstance(created_at, str) or not re.fullmatch(
|
||||
r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z",
|
||||
created_at,
|
||||
):
|
||||
raise ValueError
|
||||
|
||||
datetime.fromisoformat(created_at.replace("Z", "+00:00"))
|
||||
UUID(object_id)
|
||||
|
||||
return created_at, object_id
|
||||
|
||||
except Exception:
|
||||
raise ApiError(
|
||||
status_code=400,
|
||||
code="invalid_request",
|
||||
message="Некорректный cursor",
|
||||
)
|
||||
Reference in New Issue
Block a user