Python: 使用 cerberus 验证

Python: validation using cerberus

我想验证 dict,其中字段可能包含 intList[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

首先,int_or_list_of_intschema 应该在 int_or_list_of_int 字典中。其次,min 应该应用于整数(在 int_or_list_of_int 内)和列表(在 schema 内)。

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