验证嵌套值的问题

问题描述 投票:0回答:1

我正在尝试使用棉花糖向我的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个回答
0
投票

您仅使用Nested字段列表。无需Dict,在这里。

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

尝试一下:

class JsonSchema(BaseSchema):
    mode = fields.List(fields.Nested(ModeSchema))
© www.soinside.com 2019 - 2024. All rights reserved.