[Solved] Python, Flask: How to set response header for all responses

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

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

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?

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


Solution #1:

Set the header in a @app.after_request() hook, at which point you have a response object to set the header on:

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.

Respondent: Martijn Pieters

Solution #2:

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.

Respondent: Rafael Marques

Solution #3:

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 flask
from flask import request, g

class 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 Flask
import asyncio
from gevent.pywsgi import WSGIServer
from middleware import SimpleMiddleWare

    app = Flask(__name__)
    app.wsgi_app = SimpleMiddleWare(app.wsgi_app)
Respondent: src3369

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.