1

我想验证 a dict,其中字段可能包含 anint或 a List[int]。此外,一切都int必须是积极的。

我需要一些帮助来设置架构。下面的架构无法正常工作。他们不检查负数。也就是说,负数正在通过验证,这是不正确的。

import cerberus

v = cerberus.Validator()

schema1 = {
    "int_or_list_of_int": {
        "type": ["integer", "list"],
        "schema": {"type": "integer", "min": 0},
    },
}

schema2 = {
    "int_or_list_of_int": {
        "type": ["integer", "list"],
        "valuesrules": {"type": "integer", "min": 0},
    },
}

num1 = {"int_or_list_of_int": 5}
num2 = {"int_or_list_of_int": [5, 10]}
num3 = {"int_or_list_of_int": -5}
num4 = {"int_or_list_of_int": [5, -10]}

# schema 1
assert v.validate(num1, schema1)
assert v.validate(num2, schema1)
assert not v.validate(num3, schema1)  # Evaluates to True
assert not v.validate(num3, schema1)  # Evaluates to True

# schema 2
assert v.validate(num1, schema2)
assert v.validate(num2, schema2)to True
assert not v.validate(num3, schema2)  # Evaluates to True
assert not v.validate(num4, schema2)  # Evaluates to True
4

1 回答 1

3

首先,schemaforint_or_list_of_int应该在int_or_list_of_intdict里面。其次,min应该适用于整数(内部int_or_list_of_int)和列表(内部schema)。

schema = {
    "int_or_list_of_int": {
        "type": ["integer", "list"],
        "min": 0,
        "schema": {"type": "integer", "min": 0}
    }
}
于 2020-05-06T12:50:18.823 回答