Files
mtusi2026lab4/app/schemas.py
T

74 lines
2.4 KiB
Python

"""Request bodies. The contract forbids unknown fields, wrong types and blank strings."""
import uuid
from typing import List
from pydantic import AfterValidator, BaseModel, ConfigDict, Field, field_validator, model_validator
from typing_extensions import Annotated
def _not_blank(value: str) -> str:
if not value.strip():
raise ValueError('value must not be whitespace only')
return value
def _canonical_uuid(value: str) -> str:
parsed = uuid.UUID(value)
if str(parsed) != value.lower():
raise ValueError('value must be a canonical UUID')
return str(parsed)
Username = Annotated[str, Field(pattern=r'^[a-z0-9_]{3,32}$')]
DisplayName = Annotated[str, Field(min_length=1, max_length=100), AfterValidator(_not_blank)]
Title = Annotated[str, Field(min_length=1, max_length=100), AfterValidator(_not_blank)]
Password = Annotated[str, Field(min_length=12, max_length=128), AfterValidator(_not_blank)]
UserId = Annotated[str, AfterValidator(_canonical_uuid)]
class CreateUser(BaseModel):
model_config = ConfigDict(extra='forbid')
username: Username
display_name: DisplayName
password: Password
class CreateChat(BaseModel):
model_config = ConfigDict(extra='forbid')
title: Title
member_ids: Annotated[List[UserId], Field(min_length=1, max_length=100)]
@field_validator('member_ids')
@classmethod
def _unique(cls, value: List[str]) -> List[str]:
if len(set(value)) != len(value):
raise ValueError('member_ids must be unique')
return value
class CreateMessage(BaseModel):
"""text is required. attachment_ids defaults to [], so a lab3 body {"text": "..."} stays valid.
A blank text is accepted only together with at least one attachment.
"""
model_config = ConfigDict(extra='forbid')
text: Annotated[str, Field(max_length=4000)]
attachment_ids: Annotated[List[UserId], Field(default_factory=list, max_length=10)]
@field_validator('attachment_ids')
@classmethod
def _unique_attachments(cls, value: List[str]) -> List[str]:
if len(set(value)) != len(value):
raise ValueError('attachment_ids must be unique')
return value
@model_validator(mode='after')
def _has_content(self) -> 'CreateMessage':
if not self.text.strip() and not self.attachment_ids:
raise ValueError('text or attachment_ids is required')
return self