Add response headers to flask web app
The prettiest way to handle this, assuming that you want to same headers attached to all of your responses is with flasks builtin decorator:
@app.after_request
So in this case just add this function to your routes module:
@app.after_request
def add_security_headers(resp):
resp.headers['Content-Security-Policy']='default-src \'self\''
return resp
With this in place your functions just return the render_template(...) value as before and flask automatically wraps it in a response which is passed to the after_request function before being returned to the client.
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