如何使用 Cerberus 验证包含特定范围内的浮点数的列表?
How can I validate a list which contains floats in a specific range with Cerberus?
我想验证 JSON 个被解析为 Python 个字典的对象,如下所示:
# example with 2 elements
{
'coordinates': [-20.3, 30.6]
}
# example with 3 elements
{
'coordinates': [-20.3, 30.6, 0]
}
到目前为止,我能够定义以下架构:
schema = {
'coordinates': {
'required': True,
'type': 'list',
'minlength': 2,
'maxlength': 3,
'schema': {
'type': 'float',
},
}
}
我还想检查这些限制条件:
coordinates
字段值的第一项应介于 -30.0 和 10.0
- 第二项应介于 -10.0 和 50.0 之间
但是我想不出有用的东西。有没有人建议如何实现这一目标?
更新: 根据接受的答案,架构变为以下内容
schema = {
'coordinates': {
'required': True,
'type': 'list',
"oneof_items": (
({"min": -30.0, "max": 10.0}, {"min": -10.0, "max": 50.0}),
({"min": -30.0, "max": 10.0}, {"min": -10.0, "max": 50.0}, {}),
),
}
}
文档:https://docs.python-cerberus.org/en/stable/validation-rules.html#of-rules-typesaver
添加这条规则:
{"oneof_items":
(
({"min": -30.0, "max": 10.0}, {"min": -10.0, "max": 50.0}),
({"min": -30.0, "max": 10.0}, {"min": -10.0, "max": 50.0}, {}),
)
}
这使得与长度相关的规则变得多余。要摆脱冗余 Python 对象引用或 rule set registry 是可行的。
我想验证 JSON 个被解析为 Python 个字典的对象,如下所示:
# example with 2 elements
{
'coordinates': [-20.3, 30.6]
}
# example with 3 elements
{
'coordinates': [-20.3, 30.6, 0]
}
到目前为止,我能够定义以下架构:
schema = {
'coordinates': {
'required': True,
'type': 'list',
'minlength': 2,
'maxlength': 3,
'schema': {
'type': 'float',
},
}
}
我还想检查这些限制条件:
coordinates
字段值的第一项应介于 -30.0 和 10.0- 第二项应介于 -10.0 和 50.0 之间
但是我想不出有用的东西。有没有人建议如何实现这一目标?
更新: 根据接受的答案,架构变为以下内容
schema = {
'coordinates': {
'required': True,
'type': 'list',
"oneof_items": (
({"min": -30.0, "max": 10.0}, {"min": -10.0, "max": 50.0}),
({"min": -30.0, "max": 10.0}, {"min": -10.0, "max": 50.0}, {}),
),
}
}
文档:https://docs.python-cerberus.org/en/stable/validation-rules.html#of-rules-typesaver
添加这条规则:
{"oneof_items":
(
({"min": -30.0, "max": 10.0}, {"min": -10.0, "max": 50.0}),
({"min": -30.0, "max": 10.0}, {"min": -10.0, "max": 50.0}, {}),
)
}
这使得与长度相关的规则变得多余。要摆脱冗余 Python 对象引用或 rule set registry 是可行的。