我在Cerberus中有需要自定义验证器的验证规则。访问self.document
中的字段时,我还必须验证这些字段是否存在,即使使用"required"
标志也是如此。{2>我在找我的标志。在
例如,假设我有一个名为data
的字典,它的数组是a
和{a
和{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
存在,则此操作正常:
在
但是,如果缺少b
,它将从len()
返回一个TypeError
。
在
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']]}
以Validating that two params have same amount elements using Cerberus为灵感,可以做到:
然后:
^{pr2}$相关问题 更多 >
编程相关推荐