Python,Flask:如何为所有响应设置响应头 [英] Python, Flask: How to set response header for all responses

查看:713
本文介绍了Python,Flask:如何为所有响应设置响应头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

I want to set all of my http headers responses to something like this:

response.headers["X-Frame-Options"] = "SAMEORIGIN"

我检查了,但它只是改变了一个特定控制器的标题。我想改变我所有的头可能在before_request函数类似于下面的逻辑。

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?

@app.before_request
def before_request():
    # response.headers["X-Frame-Options"] = "SAMEORIGIN"


推荐答案

@ app.after_request() hook ,此时你有一个响应对象来设置标题:

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
def apply_caching(response):
    response.headers["X-Frame-Options"] = "SAMEORIGIN"
    return response

flask.request context 在该钩子运行时仍然可用,因此您仍然可以根据请求改变响应。

The flask.request context is still available when this hook runs, so you can still vary the response based on the request at this time.

这篇关于Python,Flask:如何为所有响应设置响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆