首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:使用cerberus进行验证

Python:使用cerberus进行验证
EN

Stack Overflow用户
提问于 2020-05-06 12:01:14
回答 1查看 302关注 0票数 1

我想验证一个dict,其中一个字段可能包含一个intList[int]。此外,所有的int必须是积极的。

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

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-06 12:50:18

首先,schema for int_or_list_of_int应该在int_or_list_of_int dict中。其次,应该将min应用于整数(在int_or_list_of_int中)和list (在schema中)。

代码语言:javascript
复制
schema = {
    "int_or_list_of_int": {
        "type": ["integer", "list"],
        "min": 0,
        "schema": {"type": "integer", "min": 0}
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61634721

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档