V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
tianxin8431
V2EX  ›  问与答

Python flask 如何让 response 按照一定的格式返回?

  •  
  •   tianxin8431 · 2020-12-16 19:23:44 +08:00 · 1067 次点击
    这是一个创建于 1198 天前的主题,其中的信息可能已经有所发展或是发生改变。

    想让每个 resp 都按照这样的三段式返回:

    {
        "data": xxx,
        "msg": xxx,
        "code": xxx
    }
    

    现在想的是用装饰器,这样可以实现视图函数的返回都按照这个来;但是有一些框架返回的东西没有办法按照这个 schema 返回,想问还有什么更好的办法吗?

    3 条回复    2020-12-16 21:50:34 +08:00
    linw1995
        1
    linw1995  
       2020-12-16 19:36:08 +08:00
    试一下 WSGI middleware ?
    zhijiansha
        2
    zhijiansha  
       2020-12-16 20:31:38 +08:00
    after_request ?
    Yuxiaoy
        3
    Yuxiaoy  
       2020-12-16 21:50:34 +08:00   ❤️ 3
    import json
    from flask import Flask, Response


    class MyResponse(Response):
    def __init__(self, response, **kwargs):
    response = json.dumps({'data': 'xxx', 'msg': 'xxx', 'code': 'xxx'})
    return super(MyResponse, self).__init__(response, **kwargs)


    app = Flask(__name__)
    app.response_class = MyResponse


    @app.route('/')
    def index():
    return 'I will be overrided'
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3592 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:29 · PVG 18:29 · LAX 03:29 · JFK 06:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.