How to Create Custom Middleware in Flask: Simple Guide
In Flask, you create custom middleware by defining a callable class that wraps the WSGI application and processes requests and responses. You implement the
__call__ method to intercept requests before they reach your routes and modify responses before they are sent back.Syntax
Custom middleware in Flask is a Python class that wraps the Flask app and implements the __call__ method. This method receives the environment and start_response callable, allowing you to process requests and responses.
- __init__(self, app): Store the Flask app instance.
- __call__(self, environ, start_response): Called on each request; you can modify the request or response here.
python
class CustomMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): # Code to run before request response = self.app(environ, start_response) # Code to run after request return response
Example
This example shows a middleware that prints a message before and after each request. It wraps the Flask app and logs to the console.
python
from flask import Flask class SimpleMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): print('Before request') response = self.app(environ, start_response) print('After request') return response app = Flask(__name__) app.wsgi_app = SimpleMiddleware(app.wsgi_app) @app.route('/') def home(): return 'Hello from Flask with middleware!' if __name__ == '__main__': app.run(debug=True)
Output
Running on http://127.0.0.1:5000/
Before request
127.0.0.1 - - [date] "GET / HTTP/1.1" 200 -
After request
Common Pitfalls
Common mistakes when creating Flask middleware include:
- Not wrapping the
app.wsgi_appbut the Flask app itself, which breaks the app. - Forgetting to call the wrapped app inside
__call__, causing no response to be returned. - Modifying the
environor response incorrectly, leading to errors.
python
class WrongMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): # Missing call to self.app, no response returned print('This will break the app') # No return statement here # Correct way: class RightMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): print('Middleware active') return self.app(environ, start_response)
Quick Reference
Tips for creating Flask middleware:
- Always wrap
app.wsgi_app, notapp. - Implement
__call__(self, environ, start_response)to intercept requests. - Call the wrapped app inside
__call__to get the response. - Use middleware for logging, authentication, or modifying requests/responses.
Key Takeaways
Create middleware by defining a callable class with __call__ that wraps app.wsgi_app.
Always call the wrapped app inside __call__ to get the response.
Wrap app.wsgi_app, not the Flask app instance itself.
Middleware can modify requests before and responses after your routes run.
Use middleware for tasks like logging, authentication, or headers modification.