简体   繁体   中英

cerberus - how to validate arbitrary dict keys?

I have read issues here and here using keysrules and valuesrules but I've only seen them validate nested not root. I'd like to valid the top level root dict keys.

schema = {
    'any_arbitrary_str': {
        'type': 'dict',
        'keysrules': {'type': 'string'},
        'valuesrules': {'type': 'integer'},
    },
}

v = Validator(schema)
v.validate({'test': {'a': 1, 'b': 2}})
print(v.errors)

In this example, I'd like to just validate that schema is dict of str: Dict[str, int] where the keys can be any arbitrary string.

I'm not sure I'm using it right docs , this fails with cerberus.schema.SchemaError: {'any_arbitrary_str': [{'keysrules': ['unknown rule'], 'valuesrules': ['unknown rule']}]} but it's still looking for any_arbitrary_str instead of any string also.

You can just nest it. Not pretty, but works. I have not found a more elegant solution yet.

schema = {
    'document': {
        'type': 'dict',
        'keysrules': {'type': 'string'},
        'valuesrules': {
            'type': 'dict',
            'keysrules': {'type': 'string'},
            'valuesrules': {'type': 'integer'},
        },
    },
}

v = Validator(schema)
document_to_test = {'test': {'a': 1, 'b': 2}}

v.validate({'document': document_to_test})
print(v.errors)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM