Pydantic 数据验证
Pydantic 验证
from datetime import datetime from typing import List, Optional from pydantic import BaseModel, EmailStr, field_validator, ValidationError def check_name(v: str) -> str: """Validator to be used throughout""" if not v.startswith("小"): raise ValueError("must be startswith 小") return v class User(BaseModel): id: int name: str = "小卤蛋" age: int # email: EmailStr signup_ts: Optional[datetime] = None friends: List[str] = [] validate_fields = field_validator("name")(check_name) @field_validator("age") # 此处在pycharm中有warning,上下顺序不能变 @classmethod def check_age(cls, age): if age < 18: raise ValueError("用户年龄必须大于18岁") return age if __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") @classmethod def check_publish_type(cls, publish_type, values): visibility = values.data.get('visibility').value if visibility == 'public': publish_type = 0 elif visibility == 'private': publish_type = 1 else: publish_type = 2 if publish_type not in [0, 1, 2]: raise ValueError("publish_type number is wrong.") return publish_type @field_validator("dept_codes") @classmethod def check_dept_codes(cls, dept_codes, values): visibility = values.data.get('visibility').value if visibility == 'internal': raise ValueError("dept_codes must be provided, can not be None or [].") return dept_codes
参考:
Pydantic:目前最流行的Python数据验证库_python pydantic-CSDN博客
Models - Pydantic