Flask视图函数返回的不仅仅是字符串,而是会对返回值进行一些列的封装,变成一个response响应对象

app.route("/hello")
def hello():
    # status 200,404,301
    # content-type http headers
    # content-type = text/html
    # Response
    return "*******"

如果视图函数单纯返回"****"的字符串的话,flask会自动进行一些封装让他变成浏览器可以读取的格式,也就是content-type = text/html,状态码为200。

我们可以使用Flask提供的make_response 方法来自定义自己的response对象

app.route("/hello")
def hello():
    # status 200,404,301
    # content-type http headers
    # content-type = text/html
    # Response
    headers = {
        'content-type':'text/plain'
    }
    # 使浏览器识别返回内容为字符串而不是html
    response = make_response("<html></html>",404)
    response.headers = headers
    
    return response

make_response()方法说明

1.返回内容

from flask import make_response

@blue.route('/makeresponse/')
def make_response_function():
    response = make_response('<h2>羞羞哒</h2>')
    return response, 404

2.返回页面

from flask import make_response

@blue.route('/makeresponse/')
def make_response_function():
    temp = render_template('hello.html')
    response = make_response(temp)
    return response

>>>注意:make_response 想要返回页面,不能直接写做:make_response('hello.html'),必须用render_template('hello.html')形式。

3.返回状态码

>>>方式一:在make_response()中传入状态码

from flask import make_response

@blue.route('/makeresponse/')
def make_response_function():
    temp = render_template('hello.html')
    response = make_response(temp, 200)
    return response

>>>方式二:直接return状态码

from flask import make_response

@blue.route('/makeresponse/')
def make_response_function():
    temp = render_template('hello.html')
    response = make_response(temp)
    return response, 200

官方文档

make_response(rv)

Convert the return value from a view function to an instance of response_class.

Parameters

rv –

the return value from the view function. The view function must return a response. Returning None, or the view ending without returning, is not allowed. The following types are allowed for view_rv:

str (unicode in Python 2) 可以传入一个字符串对象,它将被编码为UTF-8并被显示在body中

A response object is created with the string encoded to UTF-8 as the body.

bytes (str in Python 2) 

A response object is created with the bytes as the body.

dict 也可以传入一个字典类型的对象,它将被先变成json格式再返回

A dictionary that will be jsonify’d before being returned.

tuple 也可以传入一个元组,包含两个或者三个元素,分别是body内容,status状态码,headers响应头(字典类型)

Either (body, status, headers)(body, status), or (body, headers), where body is any of the other types allowed here, status is a string or an integer, and headers is a dictionary or a list of (key, value) tuples. If body is a response_class instance, status overwrites the exiting value and headers are extended.

这里的元组的意思是我们可以再函数中直接通过return来返回这三个或者两个对象,而不需要使用make_response()方法,Flask会自动进行识别和封装。

例:

app.route("/hello")
def hello():

    headers = {
        'content-type':'text/plain'
    }
    # 使浏览器识别返回内容为字符串而不是html
       
    return "<html></html>",404,headers

 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐