Middleware lets you add extra steps to handle requests and responses in your web app. It helps you run code before or after your app processes data.
Custom middleware creation in Flask
from flask import Flask, request class CustomMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): # Code before request print(f"Before request: {environ['PATH_INFO']}") def custom_start_response(status, headers, exc_info=None): # Code before response print(f"Before response: {status}") return start_response(status, headers, exc_info) return self.app(environ, custom_start_response) app = Flask(__name__) app.wsgi_app = CustomMiddleware(app.wsgi_app) @app.route('/') def home(): return "Hello from Flask!"
The middleware class wraps the Flask app's WSGI app.
The __call__ method handles each request and response.
class SimpleMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): print("Request received") return self.app(environ, start_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", "MyValue")) return start_response(status, headers, exc_info) return self.app(environ, custom_start_response)
This Flask app uses a custom middleware to print the request path before handling it and the response status before sending it back.
from flask import Flask class LoggingMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): path = environ.get('PATH_INFO', '') print(f"Request path: {path}") def custom_start_response(status, headers, exc_info=None): print(f"Response status: {status}") return start_response(status, headers, exc_info) return self.app(environ, custom_start_response) app = Flask(__name__) app.wsgi_app = LoggingMiddleware(app.wsgi_app) @app.route('/') def index(): return "Welcome to the homepage!" @app.route('/about') def about(): return "About page here."
Middleware runs for every request, so keep it fast and simple.
You can chain multiple middleware by wrapping app.wsgi_app multiple times.
Middleware works at the WSGI level, so it can handle requests before Flask routes them.
Middleware lets you add code before and after Flask handles requests.
Create a class with __call__ to wrap the Flask app.
Use middleware to log, modify, or check requests and responses easily.
Practice
Solution
Step 1: Understand middleware role
Middleware runs code around request processing, before and after Flask handles requests.Step 2: Compare options
Only To run code before and after each request is processed by Flask describes this behavior. Other options describe unrelated tasks.Final Answer:
To run code before and after each request is processed by Flask -> Option AQuick Check:
Middleware purpose = run code around requests [OK]
- Confusing middleware with route creation
- Thinking middleware replaces Flask core
- Mixing middleware with database models
Solution
Step 1: Check middleware class structure
Middleware must accept the app in __init__ and implement __call__ with environ and start_response.Step 2: Validate options
Only class MyMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): return self.app(environ, start_response) matches this pattern correctly. Others miss __call__ or parameters.Final Answer:
Correct middleware class with __init__ and __call__ methods -> Option AQuick Check:
Middleware class needs __call__ method [OK]
- Omitting __call__ method
- Not passing app to __init__
- Using function instead of class
class LoggerMiddleware:
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.wsgi_app = LoggerMiddleware(app.wsgi_app)Solution
Step 1: Analyze __call__ method
Prints 'Before request', calls app, then prints 'After request'.Step 2: Understand call order
Both prints happen on each request, before and after app call.Final Answer:
Before request printed, then After request printed -> Option DQuick Check:
Prints before and after app call [OK]
- Thinking only one print runs
- Confusing order of prints
- Assuming prints happen outside __call__
class BadMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, request):
print('Middleware active')
return self.app(request)Solution
Step 1: Check __call__ method signature
WSGI middleware __call__ must accept (environ, start_response), not (request).Step 2: Validate other parts
__init__ is correct, printing is allowed, return inside __call__ is correct.Final Answer:
__call__ method has wrong parameters; should be (environ, start_response) -> Option BQuick Check:
Middleware __call__ signature = (environ, start_response) [OK]
- Using Flask request object instead of WSGI params
- Omitting start_response parameter
- Misplacing return statement
Solution
Step 1: Understand WSGI header modification
Headers are set by calling start_response with status and headers. To add headers, wrap start_response.Step 2: Check options for correct header addition
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-Hello', 'World')) return start_response(status, headers, exc_info) return self.app(environ, custom_start_response) wraps start_response to append header before calling original start_response. Others misuse start_response or response object.Final Answer:
Wrap start_response to add header before calling original -> Option CQuick Check:
Add headers by wrapping start_response [OK]
- Calling start_response twice incorrectly
- Trying to modify response object directly in WSGI
- Adding headers to environ instead of response
Ready to prove it?
Pass the test and this pattern moves unknown
