Pydantic 校验数据
前置知识
一句话总结
Pydantic 按类型提示检查外面来的数据:把要求写成一个类,数据交给它,能转的自动转,转不了的抛出 ValidationError,说清是哪个字段、为什么不行。下单接口的参数检查,从 30 行 if 变成一个 6 行的类。
下单接口收到一段 JSON,读成字典以后,你会碰到各种样子:
{"user_id": 1, "product_id": 7, "quantity": 3} # 正常
{"user_id": 1, "product_id": 7, "quantity": "3"} # 数量是字符串
{"user_id": 1, "product_id": 7, "quantity": -5} # 数量是负数
{"user_id": 1, "quantity": 3} # 少了 product_id要是一个字段一个字段写 if 去查,有没有这个键、是不是整数、是字符串的话能不能转、在不在范围里,三四个字段就要写 30 行,而且每个接口还得再写一遍。Pydantic 是一个按类型提示检查数据的库,它让你把这些要求写成一个类。
把要求写成一个类
先装上:
uv add pydantic继承 BaseModel,像 dataclass 那样写带类型的字段:
from pydantic import BaseModel, Field
class CreateOrder(BaseModel):
user_id: int
product_id: int
quantity: int = Field(gt=0, le=99)
coupon: str | None = None这样一个类叫 Pydantic 模型。每个字段的类型就是要求:
user_id: int、product_id: int:必须有,必须是整数。quantity: int = Field(gt=0, le=99):整数,还要大于 0(gt是 greater than)、不超过 99(le是 less than or equal)。coupon: str | None = None:优惠券码,可以不传,不传就是None。
检查一段数据
把字典交给 model_validate。合格的,就造出一个 CreateOrder 对象:
order = CreateOrder.model_validate({"user_id": 1, "product_id": "7", "quantity": 3})
print(order)
print(order.quantity + 1)user_id=1 product_id=7 quantity=3 coupon=None
4传进去的 "7" 是字符串,Pydantic 把它转成了整数 7,能转的它都会帮你转;没传的 coupon 用了默认值。所以拿到对象以后,order.quantity 一定是 int,后面的代码可以放心用。
这个「检查数据合不合规矩:能转的就转,不合格就报错」的过程,叫校验。
合格的数据穿过 CreateOrder 这道门,变成一个对象,类型都转好了;不合格的在门口被拦下,错误里写着是哪个字段。
不合格时
数量是负数:
from pydantic import ValidationError
try:
CreateOrder.model_validate({"user_id": 1, "product_id": 7, "quantity": -5})
except ValidationError as e:
print(e)1 validation error for CreateOrder
quantity
Input should be greater than 0 [type=greater_than, input_value=-5, input_type=int]
For further information visit https://errors.pydantic.dev/2.14/v/greater_than少了 product_id,quantity 还是个转不成数字的 "三",两个错一起报:
2 validation errors for CreateOrder
product_id
Field required [type=missing, input_value={'user_id': 1, 'quantity': '三'}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.14/v/missing
quantity
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='三', input_type=str]
For further information visit https://errors.pydantic.dev/2.14/v/int_parsing每个错误先写字段名,再写原因:Field required 是没传,Input should be ... 是传了但不对。程序里要拿到这些信息,可以用 e.errors(),它返回一个列表,每一项是一个字典,其中 loc 是字段名,msg 是原因。
出去和进来
Pydantic 模型和字典、JSON 能互相转(文件和 JSON里是用 json 模块手动转的):
order = CreateOrder(user_id=1, product_id=7, quantity=3)
print(order.model_dump()) # 变成字典
print(order.model_dump_json()) # 变成 JSON 字符串
text = '{"user_id": 1, "product_id": 7, "quantity": 2, "coupon": "NEW10"}'
print(CreateOrder.model_validate_json(text)) # 直接读 JSON 字符串,顺便校验{'user_id': 1, 'product_id': 7, 'quantity': 3, 'coupon': None}
{"user_id":1,"product_id":7,"quantity":3,"coupon":null}
user_id=1 product_id=7 quantity=2 coupon='NEW10'直接写 CreateOrder(user_id=1, ...) 造对象,也会校验,不合格一样抛 ValidationError。
自己写检查
类型和 Field 管不到的规则,可以自己写一个方法来检查。比如收货手机号,要先去掉空格和横线,再看是不是 1 开头的 11 位数字:
from pydantic import BaseModel, field_validator
class Receiver(BaseModel):
name: str
phone: str
@field_validator("phone")
@classmethod
def check_phone(cls, v: str) -> str:
v = v.replace(" ", "").replace("-", "")
if len(v) != 11 or not v.isdigit() or not v.startswith("1"):
raise ValueError("手机号要是 1 开头的 11 位数字")
return v@field_validator("phone") 说明这个方法检查 phone 字段,它要写成 classmethod,第一个参数是类。方法返回的值就是存进对象的值,方法里抛出 ValueError 就算不合格:
print(Receiver(name="小王", phone="138 0013 8000"))
try:
Receiver(name="小王", phone="12345")
except ValidationError as e:
print(e)name='小王' phone='13800138000'
1 validation error for Receiver
phone
Value error, 手机号要是 1 开头的 11 位数字 [type=value_error, input_value='12345', input_type=str]
For further information visit https://errors.pydantic.dev/2.14/v/value_error那 dataclass 呢?它也写类型。
dataclass 只读类型提示来生成字段,并不检查。比如用 dataclass 写一个 Item,字段是 quantity: int,Item(quantity="abc") 照样造得出来,quantity 就是字符串 "abc"。所以 dataclass 适合程序里自己造的数据,外面来的数据(请求、文件、别的接口的返回)用 Pydantic。
版本提醒
本站按 Pydantic 2 写。Pydantic 1 到 2 改了很多名字:.dict() 改成 .model_dump(),.json() 改成 .model_dump_json(),parse_obj 改成 model_validate,@validator 改成 @field_validator,类里的 class Config: 改成 model_config = ConfigDict(...),orm_mode 改成 from_attributes。AI 照旧资料常写 1 的写法,在 2 上有的报弃用警告,有的直接报错。Pydantic 1 不支持 Python 3.14。
面试怎么答
问:Pydantic 和 dataclass 有什么区别?
两个都用带类型提示的字段定义一个类。dataclass 只用类型提示生成 __init__ 这些方法,不检查数据,传错类型也能造出对象。Pydantic 在造对象时按类型校验:能转的自动转,不合格就抛 ValidationError,说清哪个字段错了;它还能和字典、JSON 互相转。所以外面来的数据用 Pydantic,程序内部的数据用 dataclass 就够了。
下一篇:用 Pydantic 读配置