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

Suk*_*djf 3 post flask flask-restful marshmallow flask-marshmallow

我在 Flask 中有一个 POST 端点,它接受一个 json 数据,其中包含一个键 -collections它有一个列表作为值,而该值又包含包含特定键的字典列表。

我正在尝试验证,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)
Run Code Online (Sandbox Code Playgroud)

我试图用request.json来验证RequestSchema

我发送的内容request.json如下:

{
    "combinations": [
            {
                "nationalCustomerId": 1,
                "storeId": 1,
                "categoryId": 1,
                "deliveryDate": "2020-01-20"
            }
        ]
}
Run Code Online (Sandbox Code Playgroud)

我哪里出错了?

这是我收到的错误:

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

小智 8

你错过了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))

Run Code Online (Sandbox Code Playgroud)