从文档中,我不清楚自定义规则和自定义验证器的用例有什么区别。在文档中给出的示例中,唯一的区别是在自定义规则if
中检查值的额外语句。is_odd
我什么时候应该更喜欢自定义规则,什么时候应该更喜欢自定义验证器?
自定义规则
schema = {'amount': {'isodd': True, 'type': 'integer'}}
from cerberus import Validator
class MyValidator(Validator):
def _validate_isodd(self, isodd, field, value):
""" Test the oddity of a value.
The rule's arguments are validated against this schema:
{'type': 'boolean'}
"""
if isodd and not bool(value & 1):
self._error(field, "Must be an odd number")
自定义验证器
from cerberus import Validator
schema = {'amount': {'validator': 'oddity'}}
class AValidator(Validator):
def _validator_oddity(self, field, value):
if value & 1:
self._error(field, "Must be an odd number")