验证嵌套值的麻烦

时间:2020-03-02 20:51:37

标签: python python-3.x flask flask-restful 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."
                ]
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

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

由于您将many=True字段放在Nested字段中,因此不需要List

尝试一下:

class JsonSchema(BaseSchema):
    mode = fields.List(fields.Nested(ModeSchema))
相关问题