0
0
Flaskframework~5 mins

WSGI middleware concept in Flask

Choose your learning style9 modes available
Introduction

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.

You want to log every request and response in your web app.
You need to add security checks before your app handles requests.
You want to modify requests or responses, like adding headers.
You want to handle errors globally in one place.
You want to compress responses to make them faster to send.
Syntax
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.

Examples
This middleware prints messages before and after the app runs.
Flask
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
This middleware adds a custom header to every response.
Flask
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)
Sample Program

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.

Flask
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)
OutputSuccess
Important Notes

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.

Summary

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.