使用 Cerberus 根据条件进行依赖性验证

Dependencies validation based on conditions using Cerberus

有两个字段“field1”和“field2”。条件是“field1”或“field2”可以取 'ANY' 值,但两个字段都不能有 'ANY' 值。如何根据上述条件添加dependenciesoneofexcludes


from cerberus import Validator
v = Validator()

document = {
    "field1": "ANY",
    "field2": "ANY",
    "field3": "ANY" # This field can be ANY
}

schema = {
    "field1": {"required": True},
    "field2": {"required": True, "dependencies": {"field1": ["ANY"]},}, # I want this condition to be like "field2"shouldn´t be "ANY" if "field1" is  "ANY" and vice-versa.
}

v.validate(document, schema)  
print(v.errors)

我对架构进行了以下更改,它工作正常。


from cerberus import Validator
v = Validator()

document = {
    "field1": "ANY",
    "field2": "ANY",
    "field3": "ANY" # This field can be ANY
}

schema = {
    "field1": {"required": True, "noneof": [{"allowed": ["ANY"], "dependencies": {"field2": ["ANY"]}},]},
    "field2": {"required": True, "noneof": [{"allowed": ["ANY"], "dependencies": {"field1": ["ANY"]}},]}, 
}

v.validate(document, schema)  
print(v.errors)