Files
mtusi2026lab4/app/validation.py
T
2026-10-30 22:16:54 +03:00

83 lines
2.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Строгая валидация входа."""
import json
import re
import uuid
from .errors import ApiError, bad_request
_UUID_RE = re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
_USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}")
_INT_RE = re.compile(r"[0-9]{1,6}")
def parse_uuid(value):
if isinstance(value, str) and _UUID_RE.fullmatch(value):
return uuid.UUID(value)
return None
def require_uuid(value, name="id"):
parsed = parse_uuid(value)
if parsed is None:
raise bad_request("Некорректный %s" % name)
return parsed
def _reject_constant(name):
raise ValueError("non-finite number")
def _no_duplicates(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("duplicate key")
result[key] = value
return result
def json_body(content_type, raw, allowed, required):
if content_type.split(";")[0].strip().lower() != "application/json":
raise ApiError(415, "unsupported_media_type", "Ожидается Content-Type: application/json")
try:
data = json.loads(raw.decode("utf-8"), parse_constant=_reject_constant, object_pairs_hook=_no_duplicates)
except (ValueError, UnicodeDecodeError, RecursionError):
raise bad_request("Некорректный JSON")
if not isinstance(data, dict) or set(data) - set(allowed) or not set(required) <= set(data):
raise bad_request("Некорректный набор полей")
return data
def text_field(value, name, low, high, allow_blank=False):
if not isinstance(value, str):
raise bad_request("Поле %s должно быть строкой" % name)
if "\x00" in value or not _encodable(value):
raise bad_request("Поле %s содержит недопустимые символы" % name)
if not low <= len(value) <= high:
raise bad_request("Поле %s: длина должна быть %d–%d" % (name, low, high))
if not allow_blank and not value.strip():
raise bad_request("Поле %s не должно состоять только из пробелов" % name)
return value
def _encodable(value):
try:
value.encode("utf-8")
return True
except UnicodeEncodeError:
return False
def username_field(value):
if not isinstance(value, str) or not _USERNAME_RE.fullmatch(value):
raise bad_request("username должен соответствовать [a-z0-9_]{3,32}")
return value
def limit_param(params):
raw = params.get("limit")
if raw is None:
return 50
if not _INT_RE.fullmatch(raw) or not 1 <= int(raw) <= 100:
raise bad_request("limit должен быть целым числом 1–100")
return int(raw)