Python Package

pydantic

2025-08-20

pydantic 是 [[Python]] 最流行的数据验证库。

安装

Terminal window
pip install pydantic

使用

基本使用

from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
user = User(name="John", age=42)
print(user)

序列化

.model_dump().model_dump_json() 均包含以下参数:

  • include 指定包含的字段
  • exclude 指定排除的字段
  • by_alias 使用别名
  • exclude_defaults 排除默认值
  • exclude_none 排除 None
  • exclude_unset 排除未设置的值

测试数据:

from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel, Field
class DataModel(BaseModel):
list: Optional[List[Dict[str, Any]]] = Field(default=None, description="数据列表")
page: int = Field(default=1, description="当前页码")
page_size: int = Field(default=30, description="每页数量")
total: int = Field(default=0, description="总数据量")
class ResponseModel(BaseModel):
id: Union[str, int] = Field(description="请求ID")
success: bool = Field(default=True, description="是否成功")
data: DataModel
message: Optional[str] = Field(default=None, description="错误信息")
data = {
"id": 42,
"data": {
"list": [],
"page": 1,
"page_size": 30,
"total": 100,
},
}
response = ResponseModel(**data)

model_dump

.model_dump() 将模型转换为字典,同时子模型也会递归的转换为字典。

# 返回字典
response.model_dump()
# {'id': 42, 'success': True, 'data': {'list': [], 'page': 1, 'page_size': 30, 'total': 100}, 'message': None}
# 仅返回指定字段
response.model_dump(include={"id", "data"})
#{'id': 42, 'data': {'list': [], 'page': 1, 'page_size': 30, 'total': 100}}
# 排除指定字段
response.model_dump(exclude={"message"})
#{'id': 42, 'success': True, 'data': {'list': [], 'page': 1, 'page_size': 30, 'total': 100}}
# 使用别名
response.model_dump(by_alias=True)
# {'id': 42, 'success': True, 'data': {'list': [], 'page': 1, 'size': 30, 'total': 100}, 'message': None}
# 排除默认值
response.model_dump(exclude_defaults=True)
# {'id': 42, 'data': {'list': [], 'total': 100}}
# 排除 None
response.message = None
>>> response.model_dump(exclude_none=True)
# {'id': 42, 'success': True, 'data': {'list': [], 'page': 1, 'page_size': 30, 'total': 100}}

model_dump_json

.model_dump_json() 将模型转换为 JSON 字符串,子模型也会被转换为 JSON 字符串

# 把模型转换为 JSON
response.model_dump_json()
'{"id":42,"success":true,"data":{"list":[],"page":1,"page_size":30,"total":100},"message":null}'

错误处理

通过 pydantic 验证数据时,有时候希望能够简单的返回错误的字段和原因,写了一个简单的函数,用于提取错误信息:

from pydantic import ValidationError
def format_validation_error(e: ValidationError) -> str:
"""格式化验证错误,提取具体的字段错误信息"""
if not isinstance(e, ValidationError):
return ""
error_msgs = []
for error in e.errors():
field = ".".join(str(loc) for loc in error["loc"])
msg = f"{field}: {error['msg']}"
error_msgs.append(msg)
return "; ".join(error_msgs)

参考