如何验证映射字段是否至少有一个包含Cerberus的项目?

时间:2017-10-07 12:56:23

标签: python validation cerberus

我使用Cerberus验证文档大致如下:

{"a_dict": {"field1": "test1",
            "field2": "test2",
            "field3": "test3"}}

并非子文档中的所有字段都需要存在,但应该存在。到目前为止,我的架构看起来像这样:

"a_dict": {"type": "dict",
           "schema": {"field1": {"type": "string",
                                 "required": False},
                      "field2": {"type": "string", 
                                 "required": False},
                      "field3": {"type": "string",
                                 "required": False}}}

如何强制至少提供fieldX中的一个?

此问题源于this问题。

1 个答案:

答案 0 :(得分:1)

这就是诀窍:

string_field = {'type': 'string'}
schema = {'a_dict': {'type': 'dict',
                     'minlength': 1,
                     'allow_unknown': False,
                     'schema':
                         {f: string_field for f in ('field1', 'field2', 'field3')}
                     }}
  • minlength规则确保a_dict中至少有一个字段。
  • allow_unknown规则确保除了field<1…3>之外没有其他字段通过验证。
  • 默认情况下,required规则为False