Files
mtusi2026lab2/app/models.py
T

51 lines
1.5 KiB
Python

"""Strict request models; strings retain their original Unicode content."""
import re
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, field_validator
class Input(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid")
@field_validator("*", check_fields=False)
@classmethod
def valid_text(cls, value):
if isinstance(value, str):
if not value.strip():
raise ValueError("A string must not be blank")
value.encode("utf-8")
if "\x00" in value:
raise ValueError("NUL is not supported")
return value
class CreateUser(Input):
username: str
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
@field_validator("username")
@classmethod
def username_format(cls, value):
if re.fullmatch(r"[a-z0-9_]{3,32}", value) is None:
raise ValueError("Invalid username")
return value
class CreateChat(Input):
title: str = Field(min_length=1, max_length=100)
member_ids: list[str] = Field(min_length=1, max_length=100)
@field_validator("member_ids")
@classmethod
def members(cls, values):
normalized = [str(UUID(value)) for value in values]
if len(set(normalized)) != len(normalized):
raise ValueError("Duplicate members")
return normalized
class CreateMessage(Input):
text: str = Field(min_length=1, max_length=4000)