使用Cerberus进行依赖关系验证

时间:2019-06-21 14:36:25

标签: python validation cerberus

我正在使用Cerberus验证CSV文件,但在我认为是一些基本逻辑的情况下苦苦挣扎

场景:

CSV文件有2列。 Column 2仅在Column 1有值时才需要有值。如果Column 1为空,则Column 2也应为空。

我认为这将是编写的最直接的规则之一,但到目前为止,没有任何一项工作按预期进行。

以下是使用python字典的相同逻辑。

from cerberus import Validator
v = Validator()

schema = {
    "col1": {"required": False},
    "col2": {"required": True, "dependencies": "col1"},
}

document = {
    "col1": "a",
    "col2": ""
}

v.validate(document, schema)  # This responds with True!? Why?
v.errors
{}

在这里我会期望Column 2出现错误,因为已经提供了Column 1,但是这里的结果是True意味着没有错误

我已经检查过提出issues on github,但似乎找不到任何明显的解决方案。

2 个答案:

答案 0 :(得分:1)

  

注意
对该规则(dependencies)的评估没有考虑使用required规则定义的任何约束。< / p>

无论"required"是什么:

from cerberus import Validator
v = Validator()

document = {
    "col1": "a",
    "col2": ""
}

schema = {
    "col1": {"required": False},
    "col2": {"required": True, "dependencies": "col1"},
}

print(v.validate(document, schema))  # True
print(v.errors) # {}

schema = {
    "col1": {"required": True},
    "col2": {"required": True, "dependencies": "col1"},
}


print(v.validate(document, schema))  # True
print(v.errors)  # {}

schema = {
    "col1": {"required": True},
    "col2": {"required": False, "dependencies": "col1"},
}


print(v.validate(document, schema))  # True
print(v.errors)  # {}

http://docs.python-cerberus.org/en/stable/validation-rules.html#dependencies


更新

您的条件的解决方案“ 如果col1中包含值,则使col2为必需。”。
要应用复杂的规则,请创建一个自定义 Validator ,如下所示:

from cerberus import Validator


class MyValidator(Validator):
    def _validate_depends_on_col1(self, depends_on_col1, field, value):
        """ Test if a field value is set depending on `col1` field value.
        """
        if depends_on_col1 and self.document.get('col1', None) and not value:
            self._error(field, f"`{field}` cannot be empty given that `col1` has a value")


v = MyValidator()

schema = {
    "col1": {"required": False},
    "col2": {"required": True, "depends_on_col1": True},
}

print(v.validate({"col1": "a", "col2": ""}, schema))  # False
print(v.errors) # {'col2': ['`col2` cannot be empty given that `col1` has a value']}

print(v.validate({"col1": "", "col2": ""}, schema))  # True
print(v.errors) # {}

print(v.validate({"col1": 0, "col2": "aaa"}, schema))  # True
print(v.errors) # {}

请注意,您需要遵守将col1列的值视为空的约定(以调整自定义验证器规则)。


扩展版本以指定“依赖性”字段名称:

class MyValidator(Validator):
    def _validate_depends_on_col(self, col_name, field, value):
        """ Test if a field value is set depending on `col_name` field value.
        """
        if col_name and self.document.get(col_name, None) and not value:
            self._error(field, f"`{field}` cannot be empty given that `{col_name}` has a value")


v = MyValidator()

document = {"col1": "a", "col2": ""}

schema = {
    "col1": {"required": False},
    "col2": {"required": True, "depends_on_col": "col1"},
}

http://docs.python-cerberus.org/en/stable/customize.html

答案 1 :(得分:0)

假设您将csv输入转换为文档列表,则可以先进行预处理以删除col2字段为空的字段:

for document in documents:
    if not document["col2"]:
        document.pop("col2")

然后此架构即可完成工作:

{"col1": {
    "oneof": [
        {"empty": True},
        {"empty": False, "dependencies": "col2"}
    ]
}}

请注意,dependenciesrequired规则不考虑字段的值,而只考虑文档中字段的存在。