验证嵌套值的问题

Troubles with validating nested values

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

我正在 运行 解决如何正确验证该块的问题。最终目标是确保展示次数为正数。

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

样本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."
                ]
            }
        }
    }
}

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

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

试试这个:

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