Python, Flask: How to set response header for all responses Python, Flask: How to set response header for all responses python python

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_requestdef 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 headersdef 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.


We can set the response headers for all responses in Python Flask application gracefully using WSGI Middleware

This way of setting response headers in Flask application context using middleware is thread safe and can be used to set custom & dynamic attributes, read the request headers this is especially helpful if we are setting custom/dynamic response headers from any helper class.

file: middleware.py

import flaskfrom flask import request, gclass SimpleMiddleWare(object):    """    Simple WSGI middleware    """    def __init__(self, app):        self.app = app        self._header_name = "any_request_header"    def __call__(self, environ, start_response):        """        middleware to capture request header from incoming http request        """        request_id_header = environ.get(self._header_name)  # reading all request headers        environ[self._header_name] = request_id_header          def new_start_response(status, response_headers, exc_info=None):            """            set custom response headers            """            # set the above captured request header as response header            response_headers.append((self._header_name, request_id_header))            # example to access flask.g values set in any class thats part of the Flask app & then set that as response header            values = g.get(my_response_header, {})            if values.get('x-custom-header'):                response_headers.append(('x-custom-header', values.get('x-custom-header')))            return start_response(status, response_headers, exc_info)        return self.app(environ, new_start_response)

Calling the middleware from main class

file : main.py

from flask import Flaskimport asynciofrom gevent.pywsgi import WSGIServerfrom middleware import SimpleMiddleWare    app = Flask(__name__)    app.wsgi_app = SimpleMiddleWare(app.wsgi_app)