I'm trying to build a schema where the statement can be a single dict or a list of dicts. Ex:
{'Document': {'key': 'value'}}
Or multiple keys:
{'Document': [ {'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]}
Following the documentation I tested with this schema:
v.schema = {'Document': {'type': ['dict', 'list'], 'schema': {'type': 'dict'}}}
Here is the output:
>>> 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']}
Test code:
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)
The second case the value is a dict type but I get this error instead of getting the schema correctly interpreted.
I think the problem is due to the schema-rule and mapping, if you remove the schema rule it should work like this:
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)
More info about schema-rule and mapping:
https://docs.python-cerberus.org/en/stable/validation-rules.html#schema-dict