3

I am trying to use Cerberus to validate some data but I run into a problem.

I defined several smaller schema such as:

A = {"type": "dict", "required": False, "schema": {"name": {"type": "string"}}}

B = {"type": "dict", "required": False, "schema": {"age": {"type": "integer"}}}

C = {"type": "dict", "required": False, "schema": {"gender": {"type": "string"}}}

And the higher level schema is like:

{"something": {"type": "list", "schema": "type": [A, B, C]}}

This obviously doesn't work.

I want to validate a list, the elements in which only need to be validated by one of (A, B, C). I don't know how to do that with Cerberus and am looking for some help.

Thanks.

4

1 回答 1

5

尝试这个:

A = {"type": "dict", "schema": {"name": {"type": "string"}}}
B = {"type": "dict", "schema": {"age": {"type": "integer"}}}
C = {"type": "dict", "schema": {"gender": {"type": "string"}}}

schema = {'field':{'type':'list','anyof_schema':[A,B,C]}}

v = Validator(schema)

challenge = {'field':[{'name':'a name'}]}

v.validate(challenge)
True

这要归功于anyof_*,这是所谓的 of-rules提供的几个选项之一。这些规则允许您定义不同的规则集进行验证。如果根据前缀逻辑allanyonenone对列表中的集合进行验证,则该字段将被视为有效。有关详细信息,请参阅相关文档

于 2018-05-24T09:55:49.327 回答