WSGI middleware helps add extra features to web apps without changing their main code. It acts like a helper that sits between the web server and your app.
WSGI middleware concept in Flask
class Middleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): # Code before calling the app response = self.app(environ, start_response) # Code after calling the app return response
The app parameter is the original WSGI app your middleware wraps.
The __call__ method makes the middleware behave like a WSGI app.
class SimpleMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): print('Before app') response = self.app(environ, start_response) print('After app') return response
class HeaderMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): def custom_start_response(status, headers, exc_info=None): headers.append(('X-Custom-Header', 'Hello')) return start_response(status, headers, exc_info) return self.app(environ, custom_start_response)
This Flask app uses a simple WSGI middleware that prints messages before and after the app handles a request. When you visit the home page, you see the message from Flask, and the console shows the middleware messages.
from flask import Flask, Response class SimpleMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): print('Middleware before app') response = self.app(environ, start_response) print('Middleware after app') return response app = Flask(__name__) @app.route('/') def home(): return Response('Hello from Flask!') app.wsgi_app = SimpleMiddleware(app.wsgi_app) if __name__ == '__main__': app.run(debug=False)
Middleware can change requests or responses but should be simple to avoid slowing down your app.
Order matters: middleware wraps the app in the order you assign them.
Use middleware for cross-cutting tasks like logging, security, or compression.
WSGI middleware sits between the server and your Flask app to add extra features.
It works by wrapping the app and intercepting requests and responses.
Middleware is useful for logging, security, modifying headers, and more.