我在 Cerberus 中有需要自定义验证器的验证规则。访问 中的字段时self.document,我还必须验证这些字段是否存在,即使使用该"required"标志也是如此。我正在寻找一种方法让"required"旗帜为我处理这个问题。
例如,假设我有一个以data数组a和命名的字典,b并且规定a和b都是必需的,而len(a) == len(b).
# Schema
schema = {'data':
{'type': 'dict',
'schema': {'a': {'type': 'list',
'required': True,
'length_b': True},
'b': {'type': 'list',
'required': True}}}}
# Validator
class myValidator(cerberus.Validator):
def _validate_length_b(self, length_b, field, value):
"""Validates a field has the same length has b"""
if length_b:
b = self.document.get('b')
if not len(b) == len(value):
self._error(field, 'is not equal to length of b array')
如果a并且b存在,这可以正常工作:
good = {'data': {'a': [1, 2, 3],
'b': [1, 2, 3]}}
v = myValidator()
v.validate(good, schema)
# True
bad = {'data': {'a': [1, 2, 3],
'b': [1, 3]}}
v.validate(bad, schema)
# False
v.errors
# {'data': [{'a': ['is not equal to length of b array']}]}
但是,如果b缺少,它会返回一个TypeErrorfrom len()。
very_bad = {'data': {'a': [1, 2, 3]}}
v.validate(very_bad, schema)
# TypeError: object of type 'NoneType' has no len()
我怎样才能validate返回False(因为b不存在)?我想要的输出如下:
v.validate(very_bad, schema)
# False
v.errors
# {'data': ['b': ['required field']]}