flask第十六篇——Response【2】

今天来介绍自定义返回对象:

现在我们假定有一个需求:所有的视图函数都要返回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方法,现在这个函数就可以直接返回这个数据了:

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

原文地址:https://www.cnblogs.com/captainmeng/p/8663431.html