将响应标头添加到Flask Web应用程序 [英] Add response headers to flask web app
问题描述
我有一个flask Web应用程序,它使用如下的render_template.我需要在响应中添加一个Content-Security-Policy作为附加的http响应头.我尝试了以下方法,但都失败了,并给了我500.
I have a flask web app which uses render_template as follows.I need to add a Content-Security-Policy as additional http response headerin the response. I tried following ways but both fail and give me 500.
1.
from flask import \
Flask, \
render_template
app = Flask(__name__,template_folder='tmpl')
@app.route('/')
def index():
resp =make_response(render_template('index.html'))
resp.headers['Content-Security-Policy']='default-src \'self\''
return resp
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3001)
2.
@app.route('/')
def index():
resp =render_template('index.html')
resp.headers.add('Content-Security-Policy','default-src \'self\'')
return resp
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3001)
这有什么问题吗?
在终端上,以localhost:3001的身份访问Web应用程序时,我看到以下内容
On the terminal i see following when I access the web app as localhost:3001
127.0.0.1--[2015年4月6日01:45:01]"GET/HTTP/1.1" 500-
127.0.0.1 - - [06/Apr/2015 01:45:01] "GET / HTTP/1.1" 500 -
推荐答案
render_template
返回字符串,而不是响应.从视图返回的字符串由Flask自动包装在响应中,这就是为什么您可能会感到困惑的原因.使用呈现的模板构造响应.
render_template
returns a string, not a response. A string returned from a view is automatically wrapped in a response by Flask, which is why you may be confused. Construct the response with the rendered template.
from flask import make_response
r = make_response(render_template('index.html'))
r.headers.set('Content-Security-Policy', "default-src 'self'")
return r
这篇关于将响应标头添加到Flask Web应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!