tianxin8431
V2EX  ›  问与答

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

  •  
  •   tianxin8431 · Dec 16, 2020 · 2130 views
    This topic created in 2149 days ago, the information mentioned may be changed or developed.

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

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

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

    3 replies  •  2020-12-16 21:50:34 +08:00
    linw1995
    linw1995
    Dec 16, 2020
    1
    试一下 WSGI middleware ?
    NLL
    NLL
    Dec 16, 2020
    2
    after_request ?
    Yuxiaoy
    Yuxiaoy
    Dec 16, 2020❤️3
    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'
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1424 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 22:46 · PVG 06:46 · LAX 14:46 · JFK 17:46
    ♥ Do have faith in what you're doing.