Implement lab4 S3 attachments and reliability checks
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Request
|
||||
|
||||
from app.errors import ApiError, invalid
|
||||
|
||||
|
||||
def parse_uuid(value: object) -> UUID:
|
||||
if not isinstance(value, str):
|
||||
raise invalid("Некорректный UUID")
|
||||
|
||||
try:
|
||||
return UUID(value)
|
||||
except ValueError:
|
||||
raise invalid("Некорректный UUID") from None
|
||||
|
||||
|
||||
def valid_text(value: object, maximum: int) -> bool:
|
||||
return (
|
||||
isinstance(value, str)
|
||||
and 1 <= len(value) <= maximum
|
||||
and bool(value.strip())
|
||||
)
|
||||
|
||||
|
||||
async def read_payload(
|
||||
request: Request,
|
||||
expected_fields: set[str],
|
||||
optional_fields: set[str] | None = None,
|
||||
) -> dict:
|
||||
content_type = (
|
||||
request.headers.get("content-type", "")
|
||||
.split(";", 1)[0]
|
||||
.strip()
|
||||
.lower()
|
||||
)
|
||||
|
||||
if content_type != "application/json":
|
||||
raise ApiError(
|
||||
415,
|
||||
"unsupported_media_type",
|
||||
"Требуется Content-Type: application/json",
|
||||
)
|
||||
|
||||
try:
|
||||
payload = await request.json()
|
||||
except (ValueError, UnicodeError):
|
||||
raise invalid("Некорректный JSON") from None
|
||||
|
||||
allowed_fields = expected_fields | (optional_fields or set())
|
||||
|
||||
if (
|
||||
not isinstance(payload, dict)
|
||||
or not expected_fields.issubset(payload)
|
||||
or not set(payload).issubset(allowed_fields)
|
||||
):
|
||||
raise invalid("Некорректные поля запроса")
|
||||
|
||||
return payload
|
||||
Reference in New Issue
Block a user