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

标签 python validation cerberus

我正在使用 Cerberus验证作为 JSON 发布到基于 Flask 的 ReST-API 的数据。我希望至少存在 freight_idtender_id 这两个字段之一。

这些映射将被视为有效:

{"freight_id": 1, "price" : 12000}

{"tender_id": 1, "price": 12000}

{"freight_id": 1, "tender_id" : 2, "price": 12000}

虽然这个不会:

{"price": 12000}

如何使用 Cerberus 制定用于此类验证的模式?

我几乎阅读了所有文档,但没有找到任何答案。 excludes -规则不符合我的需要。

最佳答案

使用 cerberus 1.0,您可以使用 oneof 规则以本文档中的凝集形式实现此功能 example .有了这个,您可以针对不同的模式进行验证,其中只有一个必须验证:

缺点是你可能需要一个额外的级别,比如下面的price:

第一个架构,运费和价格:

>>> schema_1 = {'freight_id': {'type': 'integer', 'required': True},
...             'price': {'type': 'integer', 'required': True}}

第二个架构、招标和价格:

>>> schema_2 = {'tender_id': {'type': 'integer', 'required': True},
...             'price': {'type': 'integer', 'required': True}}

第三个方案,运费,标的和价格:

>>> schema_3 = {'tender_id': {'type': 'integer', 'required': True},
...             'freight_id': {'type': 'integer', 'required': True},
...             'price': {'type': 'integer', 'required': True}}

将这些放在一起:

>>> from cerberus import Validator
>>>
>>> price_validator = Validator(
...     {'price': {'type': 'dict', 
...                'oneof_schema': [schema_1, schema_2, schema_3]}})

结果:

>>> price_validator.validate({"price": {"freight_id": 1, "price" : 12000}}) 
True
>>> price_validator.validate({"price": {"tender_id": 2, "price" : 12000}})
True
>>> price_validator.validate(
...     {"price": {"freight_id": 1, "tender_id": 2, "price": 1200}}) 
True

>>> price_validator.validate({"price": {"freight_id": 1, "tender_id": 2}}) 
False 
>>> price_validator.validate({"price": {"price" : 12000}})
False

关于python - hell 犬。至少应该存在两个键之一是 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42482923/

相关文章:

python - 如何从彩色图像创建 CMYK 半色调图像?

python - 使用python请求或类似模块登录www.virtualtrader.co.uk?

javascript - 欧芹触发空字段错误

c# - 除了 try/catch 之外,是否有更好的方法来确定字符串是否可以是整数?

c# - 使用 DataAnnotations 比较两个模型属性

python - cerberus:验证可选字段至少出现一次

python - 如何使 matplotlib 显示超出图形的图例?

python - 使用 zlib 以 C 语言读取 Python 压缩数据

python - 在 Python 中使用 cerberus 验证 boolean 值