forked from mtusi2026/mtusi2026lab3
лаба на 3
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
|
||||
def encode_cursor(
|
||||
chat_id: UUID,
|
||||
created_at: datetime,
|
||||
message_id: UUID,
|
||||
) -> str:
|
||||
data = {
|
||||
"chat_id": str(chat_id),
|
||||
"created_at": created_at.isoformat(),
|
||||
"message_id": str(message_id),
|
||||
}
|
||||
|
||||
raw = json.dumps(
|
||||
data,
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii")
|
||||
|
||||
|
||||
def decode_cursor(cursor: str) -> tuple[UUID, datetime, UUID]:
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(cursor.encode("ascii"))
|
||||
|
||||
data = json.loads(raw.decode("utf-8"))
|
||||
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("Invalid cursor")
|
||||
|
||||
if set(data.keys()) != {
|
||||
"chat_id",
|
||||
"created_at",
|
||||
"message_id",
|
||||
}:
|
||||
raise ValueError("Invalid cursor")
|
||||
|
||||
chat_id = UUID(data["chat_id"])
|
||||
created_at = datetime.fromisoformat(data["created_at"])
|
||||
message_id = UUID(data["message_id"])
|
||||
|
||||
if created_at.tzinfo is None or created_at.utcoffset() is None:
|
||||
raise ValueError("Invalid cursor")
|
||||
|
||||
return chat_id, created_at, message_id
|
||||
|
||||
except (
|
||||
ValueError,
|
||||
KeyError,
|
||||
TypeError,
|
||||
UnicodeError,
|
||||
binascii.Error,
|
||||
json.JSONDecodeError,
|
||||
) as exc:
|
||||
raise ValueError("Invalid cursor") from exc
|
||||
Reference in New Issue
Block a user