如何使 cerberus 所需规则取决于条件

How to make cerberus required rule depends on condition

我有一个很大的 json 文档,如果其他字段具有精确值,则其中一些字段应该是必需的。例如

document = {'is_realty_address': False, 'postcode': 111111}

如果 is_realty_address == False,则必须提供邮政编码。 所有规则('required' 除外)都应用于文档中存在的字段,因此当我有

时,我的自定义规则是无声的
document = {'is_realty_address': False}

of-rules 对我的情况没有帮助,因为我有很多 "conditional-required" 字段,这些字段取决于许多不同的字段。因此,不规则会使我的架构复杂化。 依赖项也不起作用。我试过了:

{'postcode': {'dependencies': {'is_realty_address': False}, 'required': True}}

如果邮政编码未出现在文档中,则此 returns 错误,无论值是什么 is_realty_address

v = Validator()
print(v.validate({'is_realty_address': False}, schema))
print(v.errors)

print(v.validate({'is_realty_address': True}, schema))
print(v.errors)

此代码returns:

False
{'postcode': ['required field']}
False
{'postcode': ['required field']}

我也试过实现验证方法:

def _validate_conditional_required(self, conditional_required, field, value):
    """
    :param conditional_required:
    :param field:
    :param value:
    :return:
    The rule's arguments are validated against this schema:
    {'type': 'dict'}
    """
    for conditional_field, conditional_value in conditional_required.items():
        if self.document[conditional_field] == conditional_value and field not in self.document:
            self._error(field, errors.REQUIRED_FIELD)

有架构

schema = {
    'is_realty_address': {'required': True, 'type': 'boolean'},
    'postcode': {'conditional_required': {'is_realty_address': False}},
}

但如果 'postcode' 不在文档中,则此规则不会 运行。

有什么方法可以设置"conditional-required"规则吗? 我想看这段代码:

schema = {
    'is_realty_address': {'required': True, 'type': 'boolean'},
    'postcode': {'conditional_required': {'is_realty_address': False}},
}
v = Validator()
print(v.validate({'is_realty_address': False}, schema))
print(v.errors)

print(v.validate({'is_realty_address': True}, schema))
print(v.errors)

returns:

True

False
{'postcode': ['required field']}

我想通了,我的问题可以通过 'excludes' 和 'oneof' 规则

的组合来解决
schema = {
'is_realty_address': {
    'required': True, 'type': 'boolean',
    'oneof': [{'excludes': 'postcode', 'allowed': [False]}, {'allowed': [True]}]
},
'postcode': {'type': 'integer', 'required': True}}
v = Validator()
print(v.validate({'is_realty_address': True}, schema))
print(v.errors)

print(v.validate({'is_realty_address': False, 'postcode': 111111}, schema))
print(v.errors)

此代码returns:

False
{'postcode': ['required field']}
False
{'is_realty_address': [{'oneof': ['none or more than one rule validate', {'oneof definition 1': ['unallowed value False'], 'oneof definition 0': ["'postcode' must not be present with 'is_realty_address'"]}]}]}

因此,此变体的模式不会非常复杂。