Python: cerberus check_with function



我想验证dict,其中的值符合以下规则:

  • 值必须是单个floatList(float)
  • 如果是单个float,则该值必须为1
  • 如果是List(float),则每个浮点值必须为正

以下是我的代码和一些测试断言,它们运行正常:

import cerberus
v = cerberus.Validator()
schema1 = {
"key1": {
"type": ["float", "list"],
"min": 1,
"max": 1,
"schema": {"type": "float", "min": 0},
}
}
document1 = {"key1": 1}
document2 = {"key1": 5}
document3 = {"key1": "5"}
document4 = {"key1": [0.5, 0.3]}
document5 = {"key1": ["0.5", 0.3]}
assert v.validate(document1, schema1)
assert not v.validate(document2, schema1)
assert not v.validate(document3, schema1)
assert v.validate(document4, schema1)
assert not v.validate(document5, schema1)

现在,我必须实现另一个条件:

  • 如果是List(float),则floatsum必须等于1

因此,我编写了一个check_with函数,如文档中所述(https://docs.python-cerberus.org/en/stable/validation-rules.html)。

from cerberus import Validator
class MyValidator(Validator):
def _check_with_sum_eq_one(self, field, value):
"""Checks if sum equals 1"""
if sum(value) != 1:
self._error(field, f"Sum of '{field}' must exactly equal 1")

调整后的模式和测试文档如下所示:

v = MyValidator()
schema2 = {
"key1": {
"type": ["float", "list"],
"min": 1,
"max": 1,
"schema": {"type": "float", "min": 0, "max": 1, "check_with": "sum_eq_one"},
}
}
document1 = {"key1": 1}
document2 = {"key1": 5}
document3 = {"key1": "5"}
document4 = {"key1": [0.5, 0.3]}  # error
document5 = {"key1": ["0.5", 0.3]}  # error
document6 = {"key1": [0.5, 0.5]}  # error

现在,每当值是List(float)时,只有list的第一个元素会被注入到我的函数中,从而得到TypeError: 'float' object is not iterable
验证document4时,field将为int=0value=0.5。因此,错误消息是有意义的。

我想知道,为什么整个列表没有传递给我的函数?我在这里错过了什么?

如果您试图捕捉错误,并且只在发生错误的情况下继续执行您的函数,该怎么办?例如,像这样:

class MyValidator(Validator):
def _check_with_sum_eq_one(self, field, value):
""" Checks whether value is a list and its sum equals 1.0. """
if isinstance(value, list) and sum(value) != 1.0:
self._error(str(value), f"Sum of '{field}' must exactly equal 1")

schema2 = {
"key1": {
"type": ["list", "float"],
"min": 1,
"max": 1,
"schema": {"type": "float", "min": 0, "max": 1},
"check_with": "sum_eq_one",
}
}
v = MyValidator(schema2)
document1 = {"key1": 1}
document2 = {"key1": 5}
document3 = {"key1": "5"}
document4 = {"key1": [0.3, 0.5]}  # error
document5 = {"key1": ["0.5", 0.3]}  # error
#document6 = {"key1": [0.5, 0.5]}  # error
assert v.validate(document1)
assert not v.validate(document2)
assert not v.validate(document3)
assert v.validate(document4)
assert not v.validate(document5)

以下答案工作正常。然而,在我看来,这太复杂了。

首先,按如下方式调整schema2

schema2 = {
"key1": {
"type": ["float", "list"],
"min": 0,
"max": 1,
"check_with": "sum_eq_one"
}
}

接下来,按如下方式调整_check_with_sum_eq_one

class MyValidator(Validator):
def _check_with_sum_eq_one(self, field, value):
"""Checks if sum equals 1"""
if (isinstance(value, float) or isinstance(value, int)) and value != 1:
self._error(field, f"Sum of '{field}' must exactly equal 1")
if isinstance(value, list):
if all([isinstance(x, float) for x in value]):
if sum(value) != 1:
self._error(field, f"Sum of '{field}' must exactly equal 1")
else:
self._error(field, f"All list members must be of type ['float']")

最后,断言一切如预期。

v = MyValidator()
document1 = {"key1": 1}
document2 = {"key1": 5}
document3 = {"key1": "5"}
document4 = {"key1": [0.5, 0.3]}
document5 = {"key1": ["0.5", 0.3]}
document6 = {"key1": [0.5, 0.5]}
assert v.validate(document1, schema2)
assert not v.validate(document2, schema2)
assert not v.validate(document3, schema2)
assert not v.validate(document4, schema2)
assert not v.validate(document5, schema2)
assert v.validate(document6, schema2)

我不喜欢的是,如果所有列表成员的类型都是float(if all([isinstance(x, float) for x in value])(,我需要"手动"检查。在我看来,这个测试属于schema2。然而,在某种程度上,我没有成功地调整schema2,即float类型的测试先于check_with验证。

任何进一步简化此任务的提示都将不胜感激。

相关内容

  • 没有找到相关文章

最新更新