1

我正在使用 Cerberus 来验证具有 atype和 adata字段的有效负载。根据type(testbuild) 的值,我想data针对不同的约束进行验证。

到目前为止,我有这个设置:

test_task = {"folder": {"required": True}}
build_task = {"environment": {"allowed": ["staging", "product"]}}
abstract_task = {'type': {'allowed': ['test', 'build']},
                 'data': {'type': 'dict',
                          'required': True,
                          'anyof': [{'schema': test_task},
                                    {'schema': build_task}]}}

但是当预期的子模式失败时,也会报告关于另一个的错误:

>>> validator = cerberus.Validator(schemas.abstract_task)
>>> validator.validate({
...     "type": "build",
...     "data": {"environment": "staging"}})
>>> pp validator.errors
{'data': {'anyof': 'no definitions validated',
          'definition 0': {'environment': 'unknown field',
                           'folder': 'required field'},
          'definition 1': {'environment': 'unallowed value bad'}}}

definition 1当兄弟姐妹type具有价值时,有没有办法有条件地使用build

这个问题源于这个问题

4

1 回答 1

3

使用单一模式和验证您无法完全实现这一点,但您可以利用oneofdependencies规则来获得更清晰的错误报告:

test_task = {"folder": {"required": True}}
build_task = {"environment": {"allowed": ["staging", "product"]}}
abstract_task = {'type': {'allowed': ['test', 'build']},
                 'data': {'type': 'dict',
                          'required': True,
                          'oneof': [{'dependencies': {'type': 'test'},
                                     'schema': test_task},
                                    {'dependencies': {'type': 'build'},
                                     'schema': build_task}]}}

这就是其中一个子模式的不允许值的结果:

>>> document = {"type": "build", "data": {"environment": "legacy"}}
>>> validator(document, abstract_task)
{'data': [{'oneof': ['none or more than one rule validate',
                     {'oneof definition 0': ["depends on these values: {'type': 'test'}",
                                             {'environment': ['unknown field'],
                                              'folder': ['required field']}],
                      'oneof definition 1': [{'environment': ['unallowed value legacy']}]}
                     ]}]}
于 2017-10-07T12:18:26.597 回答