Pydantic 验证
from datetime import datetime from typing import List, Optional from pydantic import BaseModel, EmailStr, field_validator, ValidationErrordef check_name(v: str) -> str:"""Validator to be used throughout"""if not v.startswith("小"):raise ValueError("must be startswith 小")return vclass User(BaseModel):id: intname: str = "小卤蛋"age: int# email: EmailStrsignup_ts: Optional[datetime] = Nonefriends: List[str] = []validate_fields = field_validator("name")(check_name)@field_validator("age") # 此处在pycharm中有warning,上下顺序不能变@classmethoddef check_age(cls, age):if age < 18:raise ValueError("用户年龄必须大于18岁")return ageif __name__ == '__main__':user_data = {"id": 123,"name": "小卤蛋","age": 12,"email": "xiaoludan@example.com",'signup_ts': '2024-07-19 00:22','friends': ["公众号:海哥python", '小天才', b''],}try:user = User(**user_data)print(user)except ValidationError as e:print(f"Validation error: {e.json()}")
调用BaseModel内部参数作为判断条件
class RegisterParams(BaseModel):visibility: VisibilityEnum = Field(VisibilityEnum.PRIVATE)publish_type: int = Field(..., description="类型")dept_codes: List[str] = Field(..., description="部门")@field_validator("publish_type")@classmethoddef check_publish_type(cls, publish_type, values):visibility = values.data.get('visibility').valueif visibility == 'public':publish_type = 0elif visibility == 'private':publish_type = 1else:publish_type = 2if publish_type not in [0, 1, 2]:raise ValueError("publish_type number is wrong.")return publish_type@field_validator("dept_codes")@classmethoddef check_dept_codes(cls, dept_codes, values):visibility = values.data.get('visibility').valueif visibility == 'internal':raise ValueError("dept_codes must be provided, can not be None or [].")return dept_codes
参考:
Pydantic:目前最流行的Python数据验证库_python pydantic-CSDN博客
Models - Pydantic