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

如何让Flask-Marshmallow+APIFairy直接返回列表而非外层字典?

解决APIFairy返回列表时自动包裹字典的问题

APIFairy默认遵循JSON API规范,会将响应数据封装在data键的字典中。要让接口直接返回字典列表,只需修改unpaginated_response装饰器,添加raw=True参数跳过默认封装:

修改unpaginated_response装饰器

from apifairy import response

def unpaginated_response(schema):
    # 添加raw=True参数,禁用默认的data字段封装
    @response(schema(many=True), raw=True)
    def decorator(f):
        return f
    return decorator

路由使用示例

保持原有的路由写法即可,装饰器会直接返回序列化后的列表:

from .schemas import PostSchema
from .models import Post
from .decorators import unpaginated_response

@app.route('/posts')
@unpaginated_response(PostSchema)
def get_posts():
    posts = Post.query.all()
    return PostSchema(many=True).dump(posts)

这样修改后,接口就会直接返回[{}, {}, ...]格式的字典列表,不再被包裹在含data键的字典中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:20:35