gpt4 book ai didi

python - 使用 Cerberus 验证两个参数具有相同数量的元素

转载 作者:行者123 更新时间:2023-12-01 02:40:56 24 4
gpt4 key购买 nike

有没有办法拥有 Cerberus验证两个字段是否具有相同数量的元素?

例如,该文档将验证:

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

这不会:

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

到目前为止,我已经想出了这个架构:

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

但是没有规则可以测试两个字段的长度是否相等。

最佳答案

带有custom rule这非常简单:

>>> 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

关于python - 使用 Cerberus 验证两个参数具有相同数量的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45721326/

24 4 0
文章推荐: jquery - 随机定位多个图像
文章推荐: jquery - 将方法链接到返回的 JQuery 对象
文章推荐: asp.net-core - web.config、app.config 或两者?
文章推荐: jquery - 选择具有 multiple 属性的