首页 > 解决方案 > 如何通过 cerberus 验证其字段可以是 dict 或 dict 列表的数据?

问题描述

我需要验证从用户收到的字典

问题是一个字段既可以是字典也可以是字典列表。我如何用 cerberus 验证这一点?

像一个例子我尝试这个模式:

v = Validator(
    {
        'v': {
            'type': ['dict', 'list'], 
            'schema': {
                'type': 'dict', 
                'schema': {'name': {'type': 'string'}}
           }
       }
    }
)

但是当我在测试数据上尝试时,我收到错误:

v.validate({'v': {'name': '2'}})  # False
# v.errors: {'v': ['must be of dict type']}

错误:

{'v': ['must be of dict type']}

标签: pythonvalidationdictionarycerberus

解决方案


我猜内部schema是用于为字典键的值定义类型和规则(如果v是字典):

v = Validator(
    {
        'v': {
            'type': ['dict', 'list'],
            'schema': {
                'name': {'type': 'string'}
           }
       }
    }
)

print(v.validate({'v': {'name': '2'}}))
print(v.errors)

或对于列表值,如果v是列表:

v = Validator(
    {
        'v': {
            'type': ['dict', 'list'],
            'schema': {
                'type': 'integer',
           }
       }
    }
)

print(v.validate({'v': [1]}))
print(v.errors)

两种情况的正输出:

True
{}

推荐阅读