python - 使用 Cerberus 进行依赖项验证

标签 python validation cerberus

正在使用 Cerberus 验证 CSV 文件但我正在努力解决我认为的一些基本逻辑

场景:

CSV 文件有 2 列。仅当Column 1 有值时,Column 2 才需要有值。如果第 1 列 为空,则第 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但似乎找不到任何明显的解决方案。

最佳答案

Note
The evaluation of this rule (dependencies) does not consider any constraints defined with the required rule.

无论“必需”是什么:

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。”。
要应用复杂的规则 - 创建自定义验证器,如下所示:

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

关于python - 使用 Cerberus 进行依赖项验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56705509/

相关文章:

python - 使用 Kafka-python 处理生产者和消费者

python - 在 pandas 数据框中添加新列

python - 如何从 Cerberus 验证失败的文档中删除字段?

python-3.x - 使用正确的数据类型时,使用 Cerberus 验证 JSON 架构会引发错误

python - 在 python 中使用 dig 命令

python - Selenium 等待 2 个条件中的任何一个出现

具有摇动效果的 JavaScript 表单验证

php - Laravel 自定义验证规则

ajax - 使用 ajax 和 Rails 3 进行实时验证

python - Cerberus 模式验证依赖取决于自身值(value)