Files
mtusi2026lab2/app/models.py
T
2026-09-24 16:27:50 +03:00

128 lines
3.1 KiB
Python

"""
Pydantic-схемы запросов/ответов согласно contracts/openapi.json.
ВАЖНО: все модели запросов (Create*) используют extra="forbid" - контракт
явно требует 400 на JSON с лишними полями, а Pydantic по умолчанию такие
поля молча игнорирует. Без extra="forbid" лишнее поле вроде "password"
в CreateUser проходило бы валидацию незамеченным.
"""
from __future__ import annotations
import re
import uuid
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, ConfigDict, Field, field_validator
USERNAME_PATTERN = re.compile(r"^[a-z0-9_]{3,32}$")
# Пользователи
class CreateUser(BaseModel):
model_config = ConfigDict(extra="forbid")
username: str = Field(..., min_length=3, max_length=32)
display_name: str = Field(..., min_length=1, max_length=100)
@field_validator("username")
@classmethod
def check_username(cls, v: str) -> str:
if not USERNAME_PATTERN.match(v):
raise ValueError("username must match [a-z0-9_]{3,32}")
return v
@field_validator("display_name")
@classmethod
def check_display_name(cls, v: str) -> str:
if not v.strip():
raise ValueError("display_name must not be blank")
return v
class User(BaseModel):
id: uuid.UUID
username: str
display_name: str
created_at: datetime
# Чаты
class CreateChat(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(..., min_length=1, max_length=100)
member_ids: List[uuid.UUID] = Field(..., min_length=1, max_length=100)
@field_validator("title")
@classmethod
def check_title(cls, v: str) -> str:
if not v.strip():
raise ValueError("title must not be blank")
return v
@field_validator("member_ids")
@classmethod
def check_unique(cls, v: List[uuid.UUID]) -> List[uuid.UUID]:
if len(set(v)) != len(v):
raise ValueError("member_ids must be unique")
return v
class Chat(BaseModel):
id: uuid.UUID
title: str
member_ids: List[uuid.UUID]
created_at: datetime
class ChatPage(BaseModel):
items: List[Chat]
next_cursor: Optional[str] = None
# Сообщения
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(..., min_length=1, max_length=4000)
@field_validator("text")
@classmethod
def check_text(cls, v: str) -> str:
if not v.strip():
raise ValueError("text must not be blank/whitespace-only")
return v
class Message(BaseModel):
id: uuid.UUID
chat_id: uuid.UUID
sender_id: uuid.UUID
text: str
created_at: datetime
class MessagePage(BaseModel):
items: List[Message]
next_cursor: Optional[str] = None
# Health / ошибки
class Health(BaseModel):
status: str = "ok"
class ErrorBody(BaseModel):
code: str
message: str
request_id: str
class ErrorResponse(BaseModel):
error: ErrorBody