Python Cerberus: multipe schemas for a single filed?

自作多情 提交于 2019-12-07 22:44:48

问题


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.


回答1:


Try this:

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

This works thanks to the anyof_*, which is one of the several options offered by the so-called of-rules. These rules allow you to define different sets of rules to validate against. The field will be considered valid if it validates against the set in the list according to the prefixes logics all, any, one or none. For details, see the relevant documentation.



来源:https://stackoverflow.com/questions/50499045/python-cerberus-multipe-schemas-for-a-single-filed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!