如何制定cerberus规则取决于条件

时间:2018-02-14 14:33:25

标签: python json validation cerberus

我有一个大的json文档,如果其他字段具有确切的值,则需要一些字段。 E.g。

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

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

of-rules在我的案例中没有帮助,因为我有足够的"条件要求"依赖于许多不同领域的领域。因此,规则会使我的架构变得非常复杂。 依赖性也不起作用。我试过了:

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

如果邮政编码没有出现在文档中,无论有什么值,都会返回错误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)

此代码返回:

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)

with schema

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

但如果'邮政编码'此规则不会运行不在文件中。

有没有办法设置"条件要求"规则? 我想看看这段代码:

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)

返回:

True

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

1 个答案:

答案 0 :(得分:2)

我发现,我的问题可以通过'排除'和'一个'规则的组合来解决

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)

此代码返回:

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'"]}]}]}

因此,使用此变体,架构不会非常复杂。