我正在使用 Cerberus验证作为 JSON 发布到基于 Flask 的 ReST-API 的数据。我希望至少存在 freight_id
和 tender_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/