Cerberus:使用自定义有效的“必需”字段

2024-04-27 04:42:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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')

如果ab存在,则此操作正常: 在

^{pr2}$

但是,如果缺少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']]}

Tags: selftruefielddatalenschema标志type
1条回答
网友
1楼 · 发布于 2024-04-27 04:42:56

Validating that two params have same amount elements using 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)

然后:

^{pr2}$

相关问题 更多 >