forked from mtusi2026/mtusi2026lab2
56 lines
1.7 KiB
Python
56 lines
1.7 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
|
|
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)]
|
|
Text = Annotated[str, Field(min_length=1, max_length=4000), 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):
|
|
model_config = ConfigDict(extra='forbid')
|
|
|
|
text: Text
|