在Flask中使用process_response正确修改响应的方法
在一个简单的Flask应用中,我想知道在像process_response
这样的钩子里,修改响应的正确方法是什么?
比如说,给定:
from flask import Flask, Response
class MyFlask(Flask):
def process_response(self, response):
# edit response data, eg. add "... MORE!", but
# keep eg mimetype, status_code
response.data += "... This is added" # but should I modify `data`?
return response
# or should I:
# return Response(response.data + "... this is also added",
# mimetype=response.mimetype, etc)
app = MyFlask(__name__)
@app.route('/')
def root():
return "abddef"
if __name__ == '__main__':
app.run()
每次都创建一个新的响应合适吗?还是说更标准的做法是直接在原来的响应上进行修改,然后返回这个修改过的响应呢?
这可能只是风格上的问题,但我很好奇——在我阅读的资料中没有看到任何指示说哪种方式更好(尽管这可能是很常见的做法)。
谢谢你的阅读。
2 个回答
1
其实,你可以用 Flask.process_response
这个方法来拦截和修改返回的内容,方法就是这样:
from flask import Flask
import json
import ast
appVersion = 'v1.0.0'
class LocalFlask(Flask):
def process_response(self, response):
#Every response will be processed here first
response.headers['App-Version'] = appVersion
success = True if response.status_code in [ 200, 201, 204 ] else False
message = 'Ok' if success else 'Error'
dict_str = response.data.decode("UTF-8")
dataDict = ast.literal_eval(dict_str)
standard_response_data = {
'success': success,
'message': message,
'result': dataDict
}
response.data = json.dumps(standard_response_data)
super(LocalFlask, self).process_response(response)
return response
7
来自Flask.process_response的文档:
可以被重写,以便在发送响应对象到WSGI服务器之前进行修改。
响应对象是在Flask的调度机制(Flask.full_dispatch_request)中创建的。所以如果你想以自己的方式创建响应对象,可以重写Flask.make_response。只有在你想要的修改可以通过已创建的响应对象参数来完成时,才使用Flask.process_response。