PyDantic 是一个用于数据验证和设置管理的 Python 库。它通过定义数据模型来验证数据,并提供类型提示和自动生成的文档。本教程将带你从基础到高级,逐步掌握 PyDantic 的使用。
目录
1. 安装 PyDantic
首先,你需要安装 PyDantic。你可以使用 pip
来安装:
pip install pydantic
2. 基本数据模型
PyDantic 的核心是定义数据模型。你可以使用 BaseModel
类来定义一个模型。
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
email: str
在这个例子中,我们定义了一个 User
模型,包含 id
、name
和 email
三个字段。每个字段都有类型注解。
创建模型实例
你可以像创建普通类实例一样创建模型实例:
user = User(id=1, name="John Doe", email="john.doe@example.com")
print(user)
输出:
id=1 name='John Doe' email='john.doe@example.com'
访问字段
你可以通过属性访问字段:
print(user.name) # 输出: John Doe
3. 字段验证
PyDantic 会自动验证传入的数据。如果数据不符合模型的定义,PyDantic 会抛出 ValidationError
异常。
try:
user = User(id="invalid", name="John Doe", email="john.doe@example.com")
except Exception as e:
print(e)
输出:
1 validation error for User
id
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='invalid', input_type=str]
For further information visit https://errors.pydantic.dev/2.9/v/int_parsing
默认值
你可以为字段设置默认值:
class User(BaseModel):
id: int
name: str
email: str
is_active: bool = True
可选字段
你可以使用 Optional
来定义可选字段:
from typing import Optional
class User(BaseModel):
id: int
name: str
email: str
age: Optional[int] = None
4. 嵌套模型
PyDantic 支持嵌套模型。你可以将一个模型作为另一个模型的字段。
class Address(BaseModel):
street: str
city: str
zip_code: str
class User(BaseModel):
id: int
name: str
email: str
address: Address
创建嵌套模型实例:
address = Address(street="123 Main St", city="New York", zip_code="10001")
user = User(id=1, name="John Doe", email="john.doe@example.com", address=address)
print(user)
输出:
id=1 name='John Doe' email='john.doe@example.com' address=Address(street='123 Main St', city='New York', zip_code='10001')
5. 配置选项
你可以通过 Config
类来配置模型的行为。
from pydantic import BaseModel, ConfigDict, ValidationError
class Model(BaseModel):
model_config = ConfigDict(str_max_length=10)
v: str
try:
m = Model(v='x' * 20)
except ValidationError as e:
print(e)
"""
1 validation error for Model
v
String should have at most 10 characters [type=string_too_long, input_value='xxxxxxxxxxxxxxxxxxxx', input_type=str]
"""
另一种方式:
from pydantic import BaseModel, ValidationError
class Model(BaseModel, extra='forbid'):
a: str
try:
Model(a='spam', b='oh no')
except ValidationError as e:
print(e)
"""
1 validation error for Model
b
Extra inputs are not permitted [type=extra_forbidden, input_value='oh no', input_type=str]
"""
可以参考链接:https://docs.pydantic.dev/dev/concepts/config/
6. 自定义验证器
你可以使用 validator
装饰器来定义自定义验证器。
from pydantic import BaseModel, field_validator
class User(BaseModel):
id: int
name: str
email: str
@field_validator('email', mode='before')
@classmethod
def validate_email(cls, value):
if "@" not in value:
raise ValueError("Invalid email address")
return value
在这个例子中,我们定义了一个验证器来检查电子邮件地址是否包含 @
符号。
7. 错误处理
当验证失败时,PyDantic 会抛出 ValidationError
异常。你可以捕获这个异常并处理错误。
from pydantic import ValidationError
try:
user = User(id=1, name="John Doe", email="invalid-email")
except ValidationError as e:
print(e.errors())
输出:
[{'type': 'value_error', 'loc': ('email',), 'msg': 'Value error, Invalid email address', 'input': 'invalid-email', 'ctx': {'error': ValueError('Invalid email address')}, 'url': 'https://errors.pydantic.dev/2.9/v/value_error'}]