1、基本模型
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
age: int
email: str
# 自动类型转换
user = User(id="1", name="Alice", age="25", email="alice@example.com")
print(user)
# id=1 name='Alice' age=25 email='alice@example.com'
print(user.id, type(user.id)) # 1 <class 'int'>
2、字段校验与默认值
from pydantic import BaseModel, Field
from typing import Optional
class Product(BaseModel):
name: str = Field(..., min_length=1, max_length=100)
price: float = Field(..., gt=0, description="价格必须大于0")
quantity: int = Field(default=0, ge=0)
description: Optional[str] = None
p = Product(name="苹果", price=5.5)
print(p)
# name='苹果' price=5.5 quantity=0 description=None
# 校验失败会抛出 ValidationError
try:
Product(name="", price=-1)
except Exception as e:
print(e)
3、嵌套模型
from pydantic import BaseModel
from typing import List
class Address(BaseModel):
city: str
street: str
class Person(BaseModel):
name: str
age: int
addresses: List[Address]
data = {
"name": "Bob",
"age": 30,
"addresses": [
{"city": "北京", "street": "长安街"},
{"city": "上海", "street": "南京路"},
]
}
person = Person(**data)
print(person.addresses[0].city) # 北京
print(person.model_dump()) # 转 dict
print(person.model_dump_json()) # 转 JSON 字符串
4、自定义校验器
from pydantic import BaseModel, field_validator, model_validator
class User(BaseModel):
username: str
password: str
confirm_password: str
@field_validator("username")
@classmethod
def username_alphanumeric(cls, v: str) -> str:
if not v.isalnum():
raise ValueError("用户名必须为字母或数字")
return v.lower()
@model_validator(mode="after")
def check_passwords_match(self):
if self.password != self.confirm_password:
raise ValueError("两次密码不一致")
return self
u = User(username="Alice123", password="abc", confirm_password="abc")
print(u.username) # alice123
5、枚举与leteral
from pydantic import BaseModel
from enum import Enum
from typing import Literal
class Status(str, Enum):
active = "active"
inactive = "inactive"
class Account(BaseModel):
status: Status
role: Literal["admin", "user", "guest"]
a = Account(status="active", role="admin")
print(a.status) # Status.active
6、环境变量配置(baseSettings)
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
app_name: str = "MyApp"
debug: bool = False
database_url: str
model_config = {
"env_file": ".env",
"env_prefix": "APP_",
}
# .env 文件内容:
# APP_DATABASE_URL=postgresql://localhost/db
# APP_DEBUG=true
settings = Settings()
print(settings.database_url)
7、序列化与模型转换
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
password: str
u = User(id=1, name="Alice", password="secret")
# 导出时排除敏感字段
print(u.model_dump(exclude={"password"}))
# {'id': 1, 'name': 'Alice'}
# 从 ORM 对象创建(需开启 from_attributes)
class UserORM:
def __init__(self, id, name, password):
self.id = id
self.name = name
self.password = password
class UserSchema(BaseModel):
id: int
name: str
model_config = {"from_attributes": True}
orm_user = UserORM(1, "Bob", "xxx")
print(UserSchema.model_validate(orm_user))
8、泛型模型
from pydantic import BaseModel
from typing import Generic, TypeVar
T = TypeVar("T")
class Response(BaseModel, Generic[T]):
code: int
message: str
data: T
class UserInfo(BaseModel):
id: int
name: str
resp = Response[UserInfo](
code=200,
message="ok",
data={"id": 1, "name": "Alice"}
)
print(resp.data.name) # Alice