1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field, EmailStr, ValidationError, field_validator
# 1. 基本模型定义
class User(BaseModel):
id: int
name: str = Field(..., min_length=2, max_length=50) # ... 表示必填字段
email: EmailStr
age: Optional[int] = Field(None, ge=0, le=150) # ge: greater or equal, le: less or equal
created_at: datetime = Field(default_factory=datetime.now)
tags: List[str] = []
# 2. 模型使用示例
try:
# 创建用户实例
user = User(
id=1,
name="张三",
email="zhangsan@example.com",
age=25,
tags=["python", "developer"]
)
# 转换为字典
user_dict = user.model_dump()
print("转换为字典:", user_dict)
# JSON序列化
user_json = user.model_dump_json()
print("JSON序列化:", user_json)
# 数据验证失败示例
invalid_user = User(
id="不是数字", # 类型错误
name="a", # 长度不足
email="invalid_email", # 邮箱格式错误
age=200 # 超出范围
)
except ValidationError as e:
print("验证错误:", e)
# 3. 嵌套模型
class Address(BaseModel):
street: str
city: str
country: str
class UserProfile(BaseModel):
user: User
address: Address
is_active: bool = True
# 嵌套模型使用示例
profile = UserProfile(
user=User(
id=2,
name="李四",
email="lisi@example.com",
age=35,
tags=["35岁被裁员"]
),
address=Address(
street="乌鲁木齐",
city="上海",
country="中国"
)
)
# 4. 模型继承
class AdminUser(User):
admin_level: int = Field(..., ge=1, le=5)
permissions: List[str]
# 5. 复杂验证器示例
class Product(BaseModel):
name: str
price: float
quantity: int
@field_validator('price')
def validate_price(self, v):
if v < 0:
raise ValueError('价格不能为负数')
return round(v, 2)
@field_validator('quantity')
def validate_quantity(self, v):
if v < 0:
raise ValueError('数量不能为负数')
return v
|