Python Cerberus:使用“;“必需”;带有自定义验证器的字段
我在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
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']}]}