README.md 587 B

pydantic

数据验证和设置管理库,

pip install pydantic

Usage

定义一个 User model,继承 BaseModel,对年龄校验

from pydantic import (
    UUID4,
    BaseModel,
    ConfigDict,
    Field,
    InstanceOf,
    Json,
    field_validator,
    model_validator,
    EmailStr, 
    validator
)
class User(BaseModel):
    name: str
    age: int
    email: EmailStr
    phone: Optional[str] = None

    @validator("age")
    def check_age(cls, age):
        if age < 18:
            raise ValueError("用户年龄必须大于18岁")
        return age