Validating that two params have same amount elements using Cerberus

谁说我不能喝 提交于 2019-12-19 10:45:07

问题


Is there a way to have Cerberus validate that two fields have the same amount of elements?

For instance, this document would validate:

{'a': [1, 2, 3], b: [4, 5, 6]}

And this won't:

{'a': [1, 2, 3], 'b': [7, 8]}

So far I have come up with this schema:

{'a': {'required':False, 'type'= 'list', 'dependencies':'b'},
 'b': {'required':False, 'type'= 'list', 'dependencies':'a'}}

But there's no rule to test the equal length of two fields.


回答1:


With a custom rule it is pretty straight-forward:

>>> from cerberus import Validator

>>> class MyValidator(Validator):
        def _validate_match_length(self, other, field, value):
            if other not in self.document:
                return False
            if len(value) != len(self.document[other]):
                self._error(field, 
                            "Length doesn't match field %s's length." % other)

>>> schema = {'a': {'type': 'list', 'required': True},
              'b': {'type': 'list', 'required': True, 'match_length': 'a'}}
>>> validator = MyValidator(schema)
>>> document = {'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> validator(document)
True
>>> document = {'a': [1, 2, 3], 'b': [7, 8]}
>>> validator(document)
False


来源:https://stackoverflow.com/questions/45721326/validating-that-two-params-have-same-amount-elements-using-cerberus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!