python hell 犬 : multipe schemas for a single filed?

标签 python validation cerberus

我正在尝试使用 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 提供的几个选项之一。这些规则允许您定义不同的规则集来验证。如果该字段根据前缀逻辑 allanyone 针对列表中的集合进行验证,则该字段将被视为有效没有。有关详细信息,请参阅 relevant documentation .

关于 python hell 犬 : multipe schemas for a single filed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50499045/

相关文章:

python - Cerberus 依赖项如何引用文档中较高的字段?

python - hell 犬。至少应该存在两个键之一是 json

python - 使用 Cerberus 进行依赖项验证

python - Numpy 的经验密度函数

python - Ansible 模块条件要求

python - 流式 json 解析器

php - 使用 jQuery 验证插件检查一个或多个复选框(具有不同名称)是否被选中

c# - MVC 5 自定义验证在下一个选项卡之前验证

jquery - 从 django 应用程序到 jquery 插件的依赖

c# - Windows 窗体中的文本框验证