今天來介紹自定義返回對象:javascript
如今咱們假定有一個需求:全部的視圖函數都要返回json格式的對象
咱們先看一下Response
的源碼:css
發現只有一行default_mimetype='text/html'
,因此咱們須要重寫Response
類;固然咱們須要知道經常使用的數據類型:html
text/html(默認的,html文件)java
text/plain(純文本)json
text/css(css文件)flask
text/javascript(js文件)app
application/x-www-form-urlencoded(普通的表單提交)函數
multipart/form-data(文件提交)測試
application/json(json傳輸)url
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
方法,如今這個函數就能夠直接返回這個數據了:
請關注公衆號:自動化測試實戰,查看清晰排版代碼及最新更新