Python Cerberus:使用 'anyof_schema' 规则验证不同模式时出现问题

Python Cerberus: problem with validation different schemas using 'anyof_schema' rule

我正在尝试使用 Cerberus 来验证包含字符串或字典的列表,使用 anyof_schema 中建议的规则 this post:

from cerberus import Validator

A = {'type': 'dict',
     'schema': {'name': {'type': 'string', 'required': True},
                'run': {'type': 'string', 'required': True}}}
B = {'type': 'string', 'empty': False}

schema = {
    'some_field': {
        'type': 'list',
        'anyof_schema': [A, B]
    }
}

v = Validator(schema)

challenge = {
    'some_field': ['simple string 1', {'name': 'some name', 'run': 'some command'}]
}

print(v.validate(challenge))
print(v.errors)

但是验证失败,输出:

False
{'some_field': ['no definitions validate', {'anyof definition 0': [{0: ['must be of dict type']}], 'anyof definition 1': [{1: ['must be of string type']}]}]}

似乎 anyof_schema 规则仅在提供的集合中的所有模式都描述相同的数据类型(例如字典)时才有效。

为什么 anyof_schema 规则在我的案例中失败,我该如何解决这个问题?

我正在使用 Python 3.5.3 和 Cerberus 1.3.1

问题是您的架构看起来像这样扩展:

{"some_field": {
    "anyof" : [
        {"schema": …},
        {"schema": …},
    ]
}}

这意味着整个列表仅针对 anyof.

包含的每个规则集的一个变体进行验证

因此你只需要在层次结构中交换 anyofschema:

{"some_field": {
    "schema" : {
        "anyof":[
            {"type": "dict", …},
            {"type": "str", …},
        ]
    }
}}

这会根据允许的变体验证列表中的每个项目,因此这些项目可以是多种多样的 'shape'。