我正在尝试使用 Cerberus 来验证一些数据,但我遇到了问题。
我定义了几个较小的模式,例如:
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"}}}
更高层次的模式是这样的:
{"something": {"type": "list", "schema": "type": [A, B, C]}}
这显然行不通。
我想验证一个列表,其中的元素只需要被(A, B, C)
之一验证。我不知道如何用 Cerberus 做到这一点,我正在寻求帮助。
谢谢。
最佳答案
试试这个:
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 提供的几个选项之一。这些规则允许您定义不同的规则集来验证。如果该字段根据前缀逻辑 all、any、one 或 针对列表中的集合进行验证,则该字段将被视为有效没有。有关详细信息,请参阅 relevant documentation .
关于 python hell 犬 : multipe schemas for a single filed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50499045/