DAY 212 Flask response 响应对象和make_response()方法
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会自动进行识别和封装。
例:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库