Python, Flask: How to set response header for all responses
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
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.
The @app.after_request() hook
was not adequate for my use case.
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:
# 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.