flask第十六篇——Response【2】

今天来介绍自定义返回对象: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方法,如今这个函数就能够直接返回这个数据了:

 

请关注公众号:自动化测试实战,查看清晰排版代码及最新更新

相关文章
相关标签/搜索