Reputation: 55
I am trying to use Cerberus to validate a list that contains strings or dictionaries using anyof_schema
rule as proposed in 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)
But validation fails, output:
False
{'some_field': ['no definitions validate', {'anyof definition 0': [{0: ['must be of dict type']}], 'anyof definition 1': [{1: ['must be of string type']}]}]}
It seems that anyof_schema
rule works only if all schemas in the provided set describe the same data type (e.g. dictionaries).
Why anyof_schema
rule fails in my case and how can I resolve this problem?
I am using Python 3.5.3 and Cerberus 1.3.1
Upvotes: 1
Views: 2169
Reputation: 3968
The thing is that your schema looks expanded like this:
{"some_field": {
"anyof" : [
{"schema": …},
{"schema": …},
]
}}
which means that whole list is validated against only one of the variants per rules set contained by anyof.
Thus you just need to swap anyof and schema in your hierarchy:
{"some_field": {
"schema" : {
"anyof":[
{"type": "dict", …},
{"type": "str", …},
]
}
}}
This validates each item of the list against the allowed variants and these can therefore be of various 'shape'.
Upvotes: 1