You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

flask-marshmallow字段数据校验失效,Dict嵌套类型校验报错如何解决?

问题原因

你定义Schema时Dict字段的参数使用错误:marshmallow中Dict字段的构造参数顺序为Dict(key_type, value_type),你对内层Dict写的ma.Dict(ma.Integer, ma.String),代表要求内层字典的键必须为整数类型、值必须为字符串类型。但你实际传入的内层字典键是student_id、room_id这类字符串,和定义的规则冲突,所以触发了键不合法的报错。

调整方案

推荐使用结构化的Nested字段实现固定结构的内层校验,调整后的代码如下:

class RoomItemSchema(ma.Schema):
    student_id = ma.Integer(required=True)
    room_id = ma.String(required=True)

class MyRequestDto(ma.Schema):
    @pre_load
    def wrap_data(self, in_data, **kwargs):
        return {"rooms": in_data}

    rooms = ma.Dict(keys=ma.String(), values=ma.Nested(RoomItemSchema))

如果你的内层字典字段不固定,不需要做具体字段的类型校验,也可以直接调整内层Dict的参数定义:

class MyRequestDto(ma.Schema):
    @pre_load
    def wrap_data(self, in_data, **kwargs):
        return {"rooms": in_data}

    # 内层键为字符串类型,值不限制类型
    rooms = ma.Dict(ma.String, ma.Dict(ma.String, ma.Raw()))

调整后符合你要求格式的请求就可以正常通过校验了。

内容的提问来源于stack exchange,提问作者Fatima Fahad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 02:45:08