自定义响应
无纤尘
自定义响应
注意:在编写代码之前先导入Response
from flask import Flask,Response
一、如果返回的是一个合法的响应对象,则直接返回。
示例代码:
@app.route('/list/')
def list1():
return Response('list')
二、如果返回的是有个字符串,那么flask会重新创建一个werkzeug.wrappers.Response对象。Response将该字符串作为主体,
状态码为200,HTML类型为text/html,然后返回该对象。
示例代码:
@app.route('/')
def hello():
return 'hello world'
三、如果返回一个元组,元组中数据类型是(response,status,headers)。status值会覆盖默认的200状态码,headers可以是一个列表或者字典,作为额外的消息头。
示例代码:
@app.route('/list2/')
def list2():
return 'list2',200,{'x-name':'zhiliao'}
四、如果以上条件都不满足,flask会假设返回值是一个合法的WSGI应用程序,并通过Response.force_type(rv,request,environ)转换为一个请求对象。
示例代码:
这个方法只有返回非字符串,非Response对象,非元组才会调用。
class JSONResponse(Response):
@classmethod
def force_type(cls,response,environ=None):
if isinstance(response,dict):
response = jsonify(response)
return super(JSONResponse,cls).force_type(response,environ)
@app.route('/list3/')
def list3():
return {'name':'yueyue','age':'18'}
版权协议须知!
本篇文章来源于 岳岳 ,如本文章侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意
1312 0 2020-12-01