今天來介紹自定義返回對象:
現在我們假定有一個需求:所有的視圖函數都要返回json格式的對象
我們先看一下Response
的源碼:
發現只有一行default_mimetype='text/html'
,所以我們需要重寫Response
類;當然我們需要知道常用的數據類型:
-
text/html(默認的,html文件)
-
text/plain(純文本)
-
text/css(css文件)
-
text/javascript(js文件)
-
application/x-www-form-urlencoded(普通的表單提交)
-
multipart/form-data(文件提交)
-
application/json(json傳輸)
-
application/xml(xml文件)
# coding: utf-8
from flask import Flask, Response, jsonify app = Flask(__name__) # type: Flask
app.debug = True
@app.route('/')
def hello_world(): return 'Hello World!'
@app.route('/login/')
def login(): dict1 = {"name": "Warren"}
return jsonify(dict1)
@app.route('/set/')
def myset(): return u'返回元組', 200, {"name": "Warren"}
class JSONResponse(Response): default_mimetype = 'application/json' @classmethod def force_type(cls, response, environ=None): if isinstance(response, dict): response = jsonify(response)
return super(JSONResponse, cls).force_type(response, environ)
# 這個方法也需要注冊
app.response_class = JSONResponse
@app.route('/jsontext/')
def jsontext(): return {"name": "Warren"}
if __name__ == '__main__': app.run()
代碼說明,以上代碼重寫了force_type
方法,那么什么時候代碼會調用force_type
方法呢?如果返回的字符串不符合下面三種數據類型,就會調用該方法,這三種數據類型是字符串
、元組
、response
。
上面代碼里jsontext
函數直接返回dict
類型數據,本來是不可以的,但是因為我們重寫了force_type
方法,現在這個函數就可以直接返回這個數據了:
請關注公眾號:自動化測試實戰,查看清晰排版代碼及最新更新