3

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

例如,假设我有一个以data数组a和命名的字典,b并且规定ab都是必需的,而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']]}
4

1 回答 1

2

以使用 Cerberus作为灵感来验证两个参数具有相同数量的元素,可以这样做:

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']}]}
于 2018-08-14T22:27:18.053 回答