Python Cerberus:使用“;“必需”;带有自定义验证器的字段

Python Cerberus:使用“;“必需”;带有自定义验证器的字段,python,validation,cerberus,Python,Validation,Cerberus,我在Cerberus中有需要自定义验证器的验证规则。在访问self.document中的字段时,我还必须验证这些字段是否存在,即使使用“required”标志。我正在为“required”标志寻找一种方法来为我处理这个问题 例如,假设我有一个名为data的字典,其中包含数组a和b,并且规定a和b都是必需的,并且len(a)==len len(b) #模式 架构={'data': {'type':'dict', 'schema':{'a':{'type':'list', “必需”:True, 'l

我在Cerberus中有需要自定义验证器的验证规则。在访问
self.document
中的字段时,我还必须验证这些字段是否存在,即使使用
“required”
标志。我正在为
“required”
标志寻找一种方法来为我处理这个问题

例如,假设我有一个名为
data
的字典,其中包含数组
a
b
,并且规定
a
b
都是必需的,并且
len(a)==len len(b)

#模式
架构={'data':
{'type':'dict',
'schema':{'a':{'type':'list',
“必需”:True,
'length_b':True},
'b':{'type':'list',
“必需”:True}}
#验证器
类myValidator(cerberus.Validator):
定义验证长度(自身、长度、字段、值):
“”“验证与b具有相同长度的字段”“”
如果长度_b:
b=self.document.get('b')
如果不是len(b)=len(值):
self.\u错误(字段“不等于b数组的长度”)
如果出现
a
b
时,此功能正常工作:

但是,如果缺少
b
,它将从
len()
返回
TypeError

如何让
validate
返回
False
(因为
b
不存在)?我期望的输出如下:

作为灵感,我们可以做:

schema = {'data':
          {'type': 'dict',
           'schema': {'a': {'type': 'list',
                            'required': True,
                            'match_length': 'b'},
                      'b': {'type': 'list',
                            'required': True}}}}


class MyValidator(cerberus.Validator):
        def _validate_match_length(self, other, field, value):
            if other not in self.document:
                return False
            elif len(value) != len(self.document[other]):
                self._error(field, 
                            "Length doesn't match field %s's length." % other)
然后:


我很感激这是可行的,但这对我来说不是一个充分的解决方案。我的实际用例非常复杂,我不想每次都手动检查
self.document
;我希望
required
标志能帮我做到这一点。
very_bad = {'data': {'a': [1, 2, 3]}}
v.validate(very_bad, schema)
# TypeError: object of type 'NoneType' has no len()
v.validate(very_bad, schema)
# False
v.errors 
# {'data': ['b': ['required field']]}
schema = {'data':
          {'type': 'dict',
           'schema': {'a': {'type': 'list',
                            'required': True,
                            'match_length': 'b'},
                      'b': {'type': 'list',
                            'required': True}}}}


class MyValidator(cerberus.Validator):
        def _validate_match_length(self, other, field, value):
            if other not in self.document:
                return False
            elif len(value) != len(self.document[other]):
                self._error(field, 
                            "Length doesn't match field %s's length." % other)
v = MyValidator(schema)
good = {'data': {'a': [1, 2, 3],
                 'b': [1, 2, 3]}}
v.validate(good)
-> True

bad = {'data': {'a': [1, 2, 3],
                 'b': [1, 3]}}
v.validate(bad)
-> False
v.errors
-> {'data': [{'a': ["Length doesn't match field b's length."]}]}

very_bad = {'data': {'a': [1, 2, 3]}}
v.validate(very_bad)
-> False
v.errors
-> {'data': [{'b': ['required field']}]}