validator 使用装饰器可以实现自定义验证和对象之间的复杂关系。
1.校验name字段包含空格
2.校验username 必须是字母和数字组成
3.校验密码1和密码2相等
from pydantic import BaseModel, ValidationError, validator
class UserModel(BaseModel):
name: str
username: str
password1: str
password2: str
@validator('name')
def name_must_contain_space(cls, v):
if ' ' not in v:
raise ValueError('must contain a space')
return v.title()
@validator('password2')
def passwords_match(cls, v, values, **kwargs):
if 'password1' in values and v != values['password1']:
raise ValueError('passwords do not match')
return v
@validator('username')
def username_alphanumeric(cls, v):
assert v.isalnum(), 'must be alphanumeric'
return v
关于验证器的一些注意事项:
user = UserModel(
name='samuel colvin',
username='scolvin',
password1='zxcvbn',
password2='zxcvbn',
)
print(user)
print(user.dict())
运行结果:
name='Samuel Colvin' username='scolvin' password1='zxcvbn' password2='zxcvbn'
{'name': 'Samuel Colvin', 'username': 'scolvin', 'password1': 'zxcvbn', 'password2': 'zxcvbn'}
验证器可以做一些更复杂的事情:
pre=True
关键字参数pre将导致验证器在其他验证之前被调用
from pydantic import BaseModel, ValidationError, validator
from typing import List
class DemoModel(BaseModel):
friends: List[int] = []
books: List[int] = []
# '*' 在这里是匹配任意字段,包含friends,books
@validator('*', pre=True)
def split_str(cls, v):
"""如果传参是字符串,根据逗号切割成list"""
if isinstance(v, str):
return v.split(',')
return v
@validator('books')
def books_greater_then_5(cls, v):
"""判断books数量少于5"""
if len(v) > 5:
raise ValueError('books greater than 5')
return v
a1 = {
"friends": [2, 3, 4],
"books": "3,4,5"
}
d = DemoModel(**a1)
print(d) # friends=[2, 3, 4] books=[3, 4, 5]
print(d.dict()) # {'friends': [2, 3, 4], 'books': [3, 4, 5]}
虽然定义了books传list of int ,但是在校验的时候,加了个预处理,判断是字符串的时候,会转成list。
each_item=True
将导致验证器应用于单个值(例如 of List、Dict、Set等),而不是整个对象
from pydantic import BaseModel, ValidationError, validator
from typing import List
class DemoModel(BaseModel):
friends: List[int] = []
books: List[int] = []
# '*' 在这里是匹配任意字段,包含friends,books
@validator('*', pre=True)
def split_str(cls, v):
"""如果传参是字符串,根据逗号切割成list"""
if isinstance(v, str):
return v.split(',')
return v
@validator('books')
def books_greater_then_5(cls, v):
"""判断books数量少于5"""
if len(v) > 5:
raise ValueError('books greater than 5')
return v
@validator('friends', each_item=True)
def check_friends(cls, v):
"""检查friends 里面单个值数字大于1"""
assert v >= 1, f'{v} is not greater then 1'
return v
@validator('books', each_item=True)
def check_books(cls, v):
"""books 里面单个值大于2"""
assert v >= 2, f'{v} is not greater then 2'
return v
a1 = {
"friends": [2, 3, 4],
"books": "3,4,5"
}
d = DemoModel(**a1)
print(d) # friends=[2, 3, 4] books=[3, 4, 5]
print(d.dict()) # {'friends': [2, 3, 4], 'books': [3, 4, 5]}
validator传递多个字段名称,也可以传*
# '*' 在这里是匹配任意字段,包含friends,books
@validator('*', pre=True)
def split_str(cls, v):
"""如果传参是字符串,根据逗号切割成list"""
if isinstance(v, str):
return v.split(',')
return v
等价于
@validator('friends', 'books', pre=True)
def split_str(cls, v):
"""如果传参是字符串,根据逗号切割成list"""
if isinstance(v, str):
return v.split(',')
return v
如果使用带有引用List父类上的类型字段的子类的验证器,使用each_item=True将导致验证器不运行;相反,必须以编程方式迭代列表。
from typing import List
from pydantic import BaseModel, ValidationError, validator
class ParentModel(BaseModel):
names: List[str]
class ChildModel(ParentModel):
@validator('names', each_item=True)
def check_names_not_empty(cls, v):
assert v != '', 'Empty strings are not allowed.'
return v
# This will NOT raise a ValidationError because the validator was not called
try:
child = ChildModel(names=['Alice', 'Bob', 'Eve', ''])
except ValidationError as e:
print(e)
else:
print('No ValidationError caught.')
#> No ValidationError caught.
class ChildModel2(ParentModel):
@validator('names')
def check_names_not_empty(cls, v):
for name in v:
assert name != '', 'Empty strings are not allowed.'
return v
try:
child = ChildModel2(names=['Alice', 'Bob', 'Eve', ''])
except ValidationError as e:
print(e)
"""
1 validation error for ChildModel2
names
Empty strings are not allowed. (type=assertion_error)
"""
出于性能原因,默认情况下,当未提供值时,不会为字段调用验证器。但是,在某些情况下,始终调用验证器可能很有用或需要,例如设置动态默认值。
from datetime import datetime
from pydantic import BaseModel, validator
class DemoModel(BaseModel):
ts: datetime = None
@validator('ts', pre=True, always=True)
def set_ts_now(cls, v):
return v or datetime.now()
print(DemoModel())
#> ts=datetime.datetime(2021, 12, 31, 15, 4, 57, 629206)
print(DemoModel(ts='2017-11-08T14:00'))
#> ts=datetime.datetime(2017, 11, 8, 14, 0)
您经常希望将它与 一起使用pre,否则always=True pydantic会尝试验证None会导致错误的默认值。