Files
mtusi2026lab4-safronov/src/api/schemas/common.py
T
ricoromaandClaude Opus 5.5 5d5d8f9d2a chore: carry lab 3 over
- carry the lab 3 solution over from mtusi2026lab3-safronov
  (solution/bvt2301-safronov, ce89eba): src, migrations, student-tests,
  bench, openspec, .claude, infra/haproxy and infra/valkey, own scripts,
  Dockerfile, compose, pyproject and uv lock
- merge Makefile, .gitignore and .dockerignore (the lab 3 versions only
  add lines to the skeleton, which is the same in lab 4) and
  .env.example (lab 4 skeleton names listed in the header)
- rename the compose project to mtusi-lab4 and the image to :lab4 so
  the stand does not reuse the lab 3 containers and volumes
- update AGENTS.md for lab 4: current lab, origin commit, contract and
  test files of the new skeleton

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 17:32:33 +03:00

78 lines
2.5 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.
"""Общие типы HTTP-моделей: строки, UUID входа, время, ошибки, health."""
import re
from datetime import datetime
from enum import StrEnum
from typing import Annotated, Literal
from uuid import UUID
from pydantic import (
AfterValidator,
BaseModel,
BeforeValidator,
PlainSerializer,
StrictStr,
)
from src.utils.constants import UUID_PATTERN
from src.utils.utc import to_rfc3339
def _reject_blank(value: str) -> str:
"""Строка из одних пробельных символов невалидна; значение не меняется."""
if not value.strip():
raise ValueError("must not be blank")
return value
def _require_uuid_form(value: object) -> object:
"""Строка UUID — только в записи 8-4-4-4-12; не-строку разбирает `UUID`.
pydantic принимает и запись без дефисов, с `urn:uuid:` и в `{…}`, а
контракт — только `format: uuid`. Тип не-строки (массив, число, bool)
отвергает сам валидатор `UUID`.
"""
if isinstance(value, str) and not re.fullmatch(UUID_PATTERN, value):
raise ValueError("must be a UUID in 8-4-4-4-12 form")
return value
# строгая строка: число не превращается в строку; пробелы не принимаются
NonBlankStr = Annotated[StrictStr, AfterValidator(_reject_blank)]
# UUID, который передаёт клиент (путь и тело): запись контракта, цифры в
# любом регистре. Модели ответов — обычный `UUID`
UuidIn = Annotated[UUID, BeforeValidator(_require_uuid_form)]
# время в ответе: RFC 3339 UTC, всегда шесть знаков микросекунд и Z
UtcDatetime = Annotated[
datetime,
PlainSerializer(to_rfc3339, return_type=str),
]
class ErrorCode(StrEnum):
INVALID_REQUEST = "invalid_request"
UNAUTHORIZED = "unauthorized"
NOT_FOUND = "not_found"
CONFLICT = "conflict"
PAYLOAD_TOO_LARGE = "payload_too_large"
UNSUPPORTED_MEDIA_TYPE = "unsupported_media_type"
RATE_LIMITED = "rate_limited"
UNAVAILABLE = "unavailable"
INTERNAL_ERROR = "internal_error"
class ErrorBody(BaseModel):
code: ErrorCode
message: str
request_id: str
class Error(BaseModel):
error: ErrorBody
class Health(BaseModel):
status: Literal["ok"]