1

我正在尝试构建一个模式,其中语句可以是单个字典或字典列表。前任:

{'Document': {'key': 'value'}}

或多个键:

{'Document': [ {'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]}

按照我使用此架构测试的文档:

v.schema = {'Document': {'type': ['dict', 'list'], 'schema': {'type': 'dict'}}}

这是输出:

>>> v.schema = {'Document': {'type': ['dict', 'list'], 'schema': {'type': 'dict'}}}
>>> v.validate({'Document': [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]})
True
>>> v.validate({'Document': {'key': 'value'} })
False
>>> v.errors
{'Document': ['must be of dict type']}

测试代码:

import cerberus

if __name__ == '__main__':
    v = cerberus.Validator()
    v.schema = {'Document': {'type': ['dict', 'list'], 'schema': {'type': 'dict'}}}
    print(v.validate({'Document': [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]}))
    print(v.validate({'Document': {'key': 'value'}}))
    print(v.errors)

第二种情况,该值是 dict 类型,但我收到此错误,而不是正确解释架构。

4

1 回答 1

0

我认为问题是由于架构规则和映射,如果您删除架构规则,它应该像这样工作:

import cerberus

if __name__ == '__main__':
    v = cerberus.Validator()
    v.schema = {'Document': {'type': ['dict', 'list']}}
    print(v.validate({'Document': [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]}))
    print(v.validate({'Document': {'key': 'value'}}))
    print(v.errors)

有关架构规则和映射的更多信息:

https://docs.python-cerberus.org/en/stable/validation-rules.html#schema-dict

于 2021-05-12T15:00:16.593 回答