给定一个要验证的现有模型,如下面的模型(但它可以
是一个简单的字典或任何数据结构,因为 pyvaru 没有
对数据格式做出任何假设):
class User:
def __init__(self, first_name: str, last_name: str, date_of_birth: datetime, sex: str):
self.first_name = first_name
self.last_name = last_name
self.date_of_birth = date_of_birth
self.sex = sex
我们必须通过实现 get_rules() 方法来定义一个验证器
对于我们要验证的每个字段,我们必须提供一个或多个
适当的规则。
from pyvaru import Validator
from pyvaru.rules import TypeRule, FullStringRule, ChoiceRule, PastDateRule
class UserValidator(Validator):
def get_rules(self) -> list:
user = self.data # type: User
return [
TypeRule(apply_to=user,
label='User',
valid_type=User,
error_message='User must be an instance of user model.',
stop_if_invalid=True),
FullStringRule(user.first_name, 'First name'),
FullStringRule(user.last_name, 'Last name'),
ChoiceRule(user.sex, 'Sex', choices=('M', 'F')),
PastDateRule(user.date_of_birth, 'Date of birth')
]
关于如何使用我们的自定义验证器,我们有两种选择:
作为上下文处理器:
with UserValidator(user):
# do whatever you want with your valid model
在这种情况下,只有当
验证成功,否则 ValidationException(包含
带有相应报告的 validation_result 属性)被提出。
通过调用 validate() 方法(返回 ValidationResult)
validation = UserValidator(user).validate()
if validation.is_successful():
# do whatever you want with your valid model
else:
# you can take a proper action and access validation.errors
# in order to provide a useful message to the application user,
# write logs or whatever
假设我们有一个如下配置的用户实例:
user = User(first_name=' ',
last_name=None,
date_of_birth=datetime(2020, 1, 1),
sex='unknown')
通过使用之前定义的规则运行验证,我们将获得
带有以下错误的 ValidationResult:
{
'First name': ['String is empty.'],
'Last name': ['Not a string.'],
'Sex': ['Value not found in available choices.'],
'Date of birth': ['Not a past date.']
}