【问题标题】:How can I validate a list which contains floats in a specific range with Cerberus?如何使用 Cerberus 验证包含特定范围内的浮点数的列表?
【发布时间】:2020-03-10 21:31:45
【问题描述】:

我想验证解析为 Python 字典的 JSON 对象,如下所示:

# 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

【问题讨论】:

    标签: cerberus


    【解决方案1】:

    添加这条规则:

    {"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 是可行的。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 2021-02-23
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多