允许架构中的未知密钥但经过验证的值

时间:2018-06-22 19:19:35

标签: validation cerberus

验证键未知但值具有确定模式的字典的最佳方法是什么。 例如:

data = {
'name': 'test',
'department': {
    'unknown_key': {
        'known_key': 'good',
        'unknown_key': 'bad'
    }
}}

我尝试过

schema = {
'name': {
    'type': 'string'
},
'department': {
    'type': 'dict',
    'allow_unknown': {
        'schema': {
            'type': 'dict',
            'schema': {'known_key': {'type': 'string'},
                       'must_have_key': {'type': 'string'}}}
    },
}}

但是随着验证的通过,这已经失败了。丢失的must_have_keyunknown_key都应该失败。我定义错了吗?

1 个答案:

答案 0 :(得分:2)

您可以使用valueschema规则为映射中的缩写值数据定义规则:

schema = {
    'name': {'type': 'string'},
    'department': {
        'type': 'dict',
        'valueschema': {
            'type': 'dict',
            'schema':  {
                'known_key': {'type': 'string'},
                'must_have_key': {'type': 'string', 'required': True}
            }
        }
    }
}
相关问题