Flask接口返回JSON格式數據自動解析


一 自定義一個response類

from flask import Response, jsonify


# 定義response返回類,自動解析json
class JSONResponse(Response):
    @classmethod
    def force_type(cls, response, environ=None):
        if isinstance(response, dict):  # 判斷返回類型是否是字典(JSON)
            response = jsonify(response)  # 轉換
        return super().force_type(response, environ)

 

二 主類注冊app返回類

app = Flask(__name__)
app.debug = True  # 開啟debug
app.response_class = JSONResponse  # 指定返回類,解析json
# 注冊藍圖
app.register_blueprint(other, url_prefix='/other')
app.register_blueprint(user, url_prefix='/user')
app.register_blueprint(order, url_prefix='/order')


if __name__ == '__main__':
    app.run(port=8080)  # 端口默認5000

 

三 測試

視圖函數,返回元組(json),其他數據不影響:

@other.route('/json/')
def json():
    return {"name": "Sam"}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM