title: pydantic验证器Validator
date: 2020-01-17T01:20:38.127Z
tags: python,pydantic
categories: python
最近学习Python的fastapi框架,发现使用了pydantic来做输入参数。看了一下pydantic的文档,发现也可以用来做验证器。
一开始用的挺好,后来碰到一个多字段联合验证的情况,在文档里翻了一下,发现可以这么用,
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.isalpha(), 'must be alphanumeric'
return v
print(UserModel(name='samuel colvin', username='scolvin', password1='zxcvbn',
password2='zxcvbn'))
#> name='Samuel Colvin' username='scolvin' password1='zxcvbn' password2='zxcvbn'
try:
UserModel(name='samuel', username='scolvin', password1='zxcvbn',
password2='zxcvbn2')
except ValidationError as e:
print(e)
"""
2 validation errors for UserModel
name
must contain a space (type=value_error)
password2
passwords do not match (type=value_error)
"""
于是动手试了一下,结果却失败了。经过一番调试,发现,这个values,并不是所有的输入参数,只有验证通过的才有,并且不包括当前的参数,当前参数从v取。