【问题标题】:Troubles with validating nested values验证嵌套值的问题
【发布时间】:2020-03-02 20:51:37
【问题描述】:

我希望使用 Marshmallow 向我的 api 端点添加验证。

我遇到了如何正确验证这个块的问题。最终目标是确保展示次数为正数。

如果您能提供任何帮助或见解,我将不胜感激。第一次用棉花糖。

Json 示例:

{
    "mode": [
        {
            "type": "String",
            "values": {
                "visits": 1000,
                "budget": 400
            },
            "active": true
        }
    ]
}

尝试验证的示例代码

class ValidateValues(BaseSchema):
    visits = fields.Int(allow_none=True, validate=[validate.Range(min=0, error="Value must be greater than 0")])
    budget = fields.Int(allow_none=True, validate=[validate.Range(min=0, error="Value must be greater than 0")])


class ModeSchema(BaseSchema):
    type = fields.String(required=True)
    active = fields.Boolean(required=True)
    values = fields.Nested(ValidateValues)


class JsonSchema(BaseSchema):
    mode = fields.List(fields.Dict(fields.Nested(ModeSchema, many=True)))

当前结果

{
    "mode": {
        "0": {
            "type": {
                "key": [
                    "Invalid type."
                ]
            },
            "values": {
                "key": [
                    "Invalid type."
                ]
            },
            "active": {
                "key": [
                    "Invalid type."
                ]
            }
        }
    }
}

【问题讨论】:

    标签: python python-3.x flask flask-restful marshmallow


    【解决方案1】:

    您只是在使用Nested 字段的列表。不需要Dict,在这里。

    并且不需要many=True,因为您将Nested 字段放在List 字段中。

    试试这个:

    class JsonSchema(BaseSchema):
        mode = fields.List(fields.Nested(ModeSchema))
    

    【讨论】:

      猜你喜欢
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多