如何根据Cerberus的另一个字段的长度来验证字段?

时间:2017-12-14 09:56:47

标签: python cerberus

有没有办法验证一个字段的存在取决于其他字段的长度的文件? 我的尝试:

import cerberus

schema = {
    'field_2': {
        'type': 'integer',
        'dependencies': {
            'field_1': {'maxlength': 1}
        }
    },
    'field_1': {
        'type': 'list',
    }
}
v = cerberus.Validator(schema)
doc = {
    'field_1': [1, ],
    'field_2': 77
}
if not v.validate(doc):
    print(v.errors)
else:
    print(True)

输出:

{'field_2': ["depends on these values: {'field_1': {'maxlength': 1}}"]}

预期输出为True

2 个答案:

答案 0 :(得分:2)

可以使用custom rules

完成
from typing import Optional, Any, Tuple

from cerberus import Validator


class ExtendedValidator(Validator):
    def _validate_with_length(self, with_length, field, _value):
        # type: (Tuple[str, int], str, Any) -> Optional[bool]
        """Validating in dependence of length of other field in document

        The rule's arguments are validated against this schema:
        {'type': 'list'}
        """
        key, length = with_length
        if key not in self.document:
            return False
        if len(self.document[key]) != length:
            self._error(field, "Length of %s must be %s" % (key, length))


schema = {
    'field_2': {
        'type': 'integer',
        'with_length': ('field_1', 1),
    },
    'field_1': {
        'type': 'list',
    }
}

docs = [{'field_1': [1, ], 'field_2': 77}, {'field_1': [1, 2], 'field_2': 77}]
v = ExtendedValidator(schema)
for doc in docs:
    if not v.validate(doc):
        print(v.errors)
    else:
        print(True)

输出:

True
{'field_2': ['Length of field_1 must be 1']}

答案 1 :(得分:0)

有意义吗?将'maxlength': 1移至field_1定义。

schema = {
    'field_2': {
        'type': 'integer',
        'dependencies': 'field_1'
    },
    'field_1': {
        'type': 'list',
        'maxlength': 1
    }
}