Cerberus には、カスタム バリデータを必要とする検証ルールがあります。のフィールドにアクセスするときは、フラグself.documentを使用している場合でも、それらのフィールドが存在することも検証する必要があります。フラグがこれを処理"required"する方法を探しています。"required"
たとえば、data配列aとで指定された辞書があり、との両方が必要であり、 でbあるという規定があるとします。ablen(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']}]}
ただし、 がない場合はfrom をb返します。
TypeErrorlen()
very_bad = {'data': {'a': [1, 2, 3]}}
v.validate(very_bad, schema)
# TypeError: object of type 'NoneType' has no len()
代わりに(存在しないため)validate戻るにはどうすればよいですか?私の望ましい出力は以下の通りです:
Falseb
v.validate(very_bad, schema)
# False
v.errors
# {'data': ['b': ['required field']]}