1. 程式人生 > 程式設計 >Flask介面如何返回JSON格式資料自動解析

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"}

Flask介面如何返回JSON格式資料自動解析

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。