ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

DAY 212 Flask response 响应对象和make_response()方法

2021-10-24 17:35:02  阅读:150  来源: 互联网

标签:body return Flask make headers 212 response view


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

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

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

make_response()方法说明

1.返回内容

 2.返回页面

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

3.返回状态码

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

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

官方文档
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会自动进行识别和封装。

例:

 

标签:body,return,Flask,make,headers,212,response,view
来源: https://www.cnblogs.com/DEJAVU888/p/15451957.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有