基于规则的python数据验证库。
pyvaru的Python项目详细描述
什么是皮瓦鲁?
从软件设计的角度来看,规则是实现策略模式的类, 通过将验证逻辑封装在名为apply()的接口方法中。
该库已经提供了一系列常见的验证规则,如:
- TypeRule(它检查目标值是否是预期类型的实例)
- FullStringRule(它检查目标值是否是包含内容的字符串)
- ChoiceRule(它检查目标值是否包含在可用选项列表中)
- MinValueRule(它检查目标值是否为>;=x)*
- MaxValueRule(它检查目标值是否为<;=x)*
- MinLengthRule(它检查目标值长度是否为>;=x)*
- MaxLengthRule(它检查目标值长度是否为<;=x)*
- RangeRule(它检查目标值是否包含在给定的range)中
- IntervalRule(它检查目标值是否包含在给定的间隔中)
- PatternRule(它检查目标值是否与给定的正则表达式匹配)
- PastDateRule(它检查目标值是否是过去的日期)
- FutureDateRule(它检查目标值是否为将来的日期)
- UniqueItemsRule(它检查目标iterable是否不包含重复项)
*其中“x”是提供的参考值
然后,开发人员可以通过扩展抽象的^{tt16}来创建他的自定义规则。$ 在apply()方法中实现逻辑。例如:
classContainsHelloRule(ValidationRule):defapply(self)->bool:return'hello'inself.apply_to
然后由Validator执行这些规则,它基本上在提供的 排序并最终返回包含验证响应的ValidationResult。
安装
pip install pyvaru
用法
<给定一个现有的模型来验证,如下面的 (但它可以是一个简单的字典或任何数据结构,因为pyvaru 对数据格式不作任何假设:classUser:def__init__(self,first_name:str,last_name:str,date_of_birth:datetime,sex:str):self.first_name=first_nameself.last_name=last_nameself.date_of_birth=date_of_birthself.sex=sex
我们必须定义一个验证器,通过实现get_rules()方法并为每个我们想要的字段 验证我们必须提供一个或多个正确的规则。
frompyvaruimportValidatorfrompyvaru.rulesimportTypeRule,FullStringRule,ChoiceRule,PastDateRuleclassUserValidator(Validator):defget_rules(self)->list:user=self.data# type: Userreturn[TypeRule(apply_to=user,label='User',valid_type=User,error_message='User must be an instance of user model.',stop_if_invalid=True),FullStringRule(lambda:user.first_name,'First name'),FullStringRule(lambda:user.last_name,'Last name'),ChoiceRule(lambda:user.sex,'Sex',choices=('M','F')),PastDateRule(lambda:user.date_of_birth,'Date of birth')]
也可以使用RuleGroup创建规则组,如果多个规则应该 应用于同一个字段。所以这个代码:
defget_rules(self)->list:return[TypeRule(lambda:self.data.countries,'Countries',valid_type=list),MinLengthRule(lambda:self.data.countries,'Countries',min_length=1),UniqueItemsRule(lambda:self.data.countries,'Countries')]
可替换为:
defget_rules(self)->list:return[RuleGroup(lambda:self.data.countries,'Countries',rules=[(TypeRule,{'valid_type':list}),(MinLengthRule,{'min_length':1}),UniqueItemsRule])]
最后,关于如何使用我们的自定义验证器,我们有两个选择:
- 作为上下文处理器:
withUserValidator(user):# do whatever you want with your valid model
在这种情况下,with中的代码只有在验证成功时才会执行,否则 ValidationException(包含带有相应报表的validation_result属性)被引发。
- 通过调用validate()方法(返回ValidationResult)
validation=UserValidator(user).validate()ifvalidation.is_successful():# do whatever you want with your valid modelelse:# 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.']}