ЛР 2: мессенджер на PostgreSQL и сессии в Redis
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
import base64
|
||||
import json
|
||||
from uuid import UUID
|
||||
|
||||
from ..domain.errors import Invalid
|
||||
from ..domain.models import Keyset
|
||||
from .timefmt import from_rfc3339, to_rfc3339
|
||||
|
||||
MAX_LENGTH = 512
|
||||
|
||||
|
||||
def encode(scope: str, position: Keyset) -> str:
|
||||
payload = {'s': scope, 't': to_rfc3339(position.created_at), 'i': str(position.id)}
|
||||
raw = json.dumps(payload, separators=(',', ':'), sort_keys=True).encode('utf-8')
|
||||
return base64.urlsafe_b64encode(raw).decode('ascii').rstrip('=')
|
||||
|
||||
|
||||
def decode(scope: str, value: str) -> Keyset:
|
||||
if not value or len(value) > MAX_LENGTH:
|
||||
raise Invalid('cursor недействителен для этого запроса')
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(value + '=' * (-len(value) % 4))
|
||||
payload = json.loads(raw)
|
||||
if not isinstance(payload, dict) or payload.get('s') != scope:
|
||||
raise ValueError('scope mismatch')
|
||||
return Keyset(created_at=from_rfc3339(payload['t']), id=UUID(payload['i']))
|
||||
except Exception:
|
||||
raise Invalid('cursor недействителен для этого запроса') from None
|
||||
Reference in New Issue
Block a user