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)
X-Frame-Options
has been obsoleted by theframe-ancestors
directive. More info on frame-ancestors w3.org/TR/CSP2/#directive-frame-ancestors and an open-source lib to imlpement Flask CSP: github.com/twaldear/flask-csp – Abagael