Python,Flask:如何为所有响应设置响应标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30717152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python, Flask: How to set response header for all responses
提问by Saeid
I want to set all of my http headers responses to something like this:
我想将我所有的 http 标头响应设置为这样的:
response.headers["X-Frame-Options"] = "SAMEORIGIN"
I checked this question, but it only changes the header for one specific controller. I want to change all of my headers maybe in "before_request" function similar to the following logic. How can I do that?
我检查了这个问题,但它只更改了一个特定控制器的标题。我想在类似于以下逻辑的“before_request”函数中更改我的所有标头。我怎样才能做到这一点?
@app.before_request
def before_request():
# response.headers["X-Frame-Options"] = "SAMEORIGIN"
采纳答案by Martijn Pieters
Set the header in a @app.after_request()hook, at which point you have a response object to set the header on:
在@app.after_request()hook 中设置标题,此时您有一个响应对象来设置标题:
@app.after_request
def apply_caching(response):
response.headers["X-Frame-Options"] = "SAMEORIGIN"
return response
The flask.requestcontextis still available when this hook runs, so you can still vary the response based on the request at this time.
的flask.request背景下仍然可以在这个钩子运行,所以你仍然可以改变基于此时的请求的响应。
回答by Rafael Marques
The @app.after_request() hookwas not adequate for my use case.
这@app.after_request() hook对于我的用例来说是不够的。
My use case is as follows: I have a google cloud function, and I want to set the CORS headers for all responses. There are possibly multiple responses, as I have to validate the input and return if there are issues with it, I have to process data and possibly return early if something fails etc. So I've created a helper function as follows:
我的用例如下:我有一个谷歌云功能,我想为所有响应设置 CORS 标头。可能有多个响应,因为我必须验证输入并在出现问题时返回,我必须处理数据并可能在出现故障时尽早返回等。所以我创建了一个辅助函数,如下所示:
# Helper function to return a response with status code and CORS headers
def prepare_response(res_object, status_code):
response = flask.jsonify(res_object)
response.headers.set('Access-Control-Allow-Origin', '*')
response.headers.set('Access-Control-Allow-Methods', 'GET, POST')
return response, status_code
Thus, when I want to return a response (always with CORS headers), I can now call this function and I do not duplicate the response.headers setup necessary to enable CORS.
因此,当我想返回一个响应(总是带有 CORS 标头)时,我现在可以调用这个函数并且我不会重复启用 CORS 所需的 response.headers 设置。

![python中for循环中的[]括号是什么意思?](/res/img/loading.gif)