如何验证棉花糖中特定类型的元素列表?

时间:2020-02-12 22:00:49

标签: post flask flask-restful marshmallow flask-marshmallow

我在flask中有一个POST端点,该端点接收一个包含密钥的collections json数据,该密钥具有一个列表作为值,而该列表又包含其中包含特定密钥的字典列表。

我正在尝试验证request.json,但找不到正确的方法。

这是棉花糖模式的代码:

class RowSchema(Schema):
    nationalCustomerId = fields.Int(required=True)
    storeId = fields.Int(required=True)
    categoryId = fields.Int(required=True)
    deliveryDate = fields.Date(required=True, format="%Y-%m-%d")

class RequestSchema(Schema):
    combinations = fields.List(RowSchema)

我试图用request.json验证RequestSchema

我发送的request.json如下:

{
    "combinations": [
            {
                "nationalCustomerId": 1,
                "storeId": 1,
                "categoryId": 1,
                "deliveryDate": "2020-01-20"
            }
        ]
}

我在哪里犯错?

这是我得到的错误:

ValueError:列表元素必须是的子类或实例 marshmallow.base.FieldABC。

1 个答案:

答案 0 :(得分:2)

您错过了fields.Nested内的fields.List

class RowSchema(Schema):
    nationalCustomerId = fields.Int(required=True)
    storeId = fields.Int(required=True)
    categoryId = fields.Int(required=True)
    deliveryDate = fields.Date(required=True, format="%Y-%m-%d")

class RequestSchema(Schema):
    combinations = fields.List(fields.Nested(RowSchema))