FastAPI对自定义的类进行校验
@router.post("/")
async def create(request: Request, my_model: MyModel = Body(...)):
from typing import Optional, Dict, List
from pydantic import Field, BaseModel, field_validator, constr
class MyModel(BaseModel):
a: Dict[str, str] = Field(...)
b: List[constr(min_length=1)] = Field(..., min_items=1)
c: str = Field(min_length=1)
d: str = Field(min_length=1)
@field_validator("a")
def valid_a(cls, value: Dict[str, str]):
if (not value) or len(value) == 0:
raise ValueError("`a` is required and cannot by empty")
return value