Pydantic 是一个基于 Python 类型注解的数据验证与序列化库,其设计哲学强调"数据正确性优先"。通过声明式模型定义,开发者可以:
from pydantic import BaseModel, ValidationError
class UserProfile(BaseModel):
user_id: int
username: str = "匿名用户"
email: str | None = None
credit_score: float = Field(ge=0, le=1000) # 数值范围约束
try:
profile = UserProfile(user_id="1024", credit_score=1200)
except ValidationError as e:
print(e.errors())
# 输出:[{
# "loc": ("user_id",),
# "msg": "输入类型不是整数",
# "type": "type_error.integer"
# }, {
# "loc": ("credit_score",),
# "msg": "输入值应小于等于1000",
# "type": "value_error.number.not_le"
# }]
自定义校验器
通过装饰器实现复杂业务规则:
from pydantic import validator
class Product(BaseModel):
sku: str
price