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.
Practice
Solution
Step 1: Understand WSGI middleware position
WSGI middleware acts as a layer between the web server and the Flask app, intercepting requests and responses.Step 2: Identify middleware purpose
It modifies or adds features like logging or security without replacing the app or handling unrelated tasks.Final Answer:
To sit between the server and the Flask app to modify requests or responses -> Option CQuick Check:
Middleware = intercepts requests/responses [OK]
- Thinking middleware replaces the app
- Confusing middleware with static file serving
- Assuming middleware manages database connections
MyMiddleware?Solution
Step 1: Recall middleware wrapping syntax
WSGI middleware wraps the Flask app by passing the app instance to the middleware constructor.Step 2: Match correct syntax
The correct syntax is assigning the wrapped app back toappusingapp = MyMiddleware(app).Final Answer:
app = MyMiddleware(app) -> Option AQuick Check:
Wrap app by passing it to middleware constructor [OK]
- Calling middleware as a method on app
- Not assigning wrapped app back to a variable
- Assigning middleware class without instantiation
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
app = Flask(__name__)
app = SimpleMiddleware(app)Solution
Step 1: Analyze middleware call flow
The middleware prints 'Before app' before calling the wrapped app, then prints 'After app' after the app returns.Step 2: Understand request handling
When a request comes, both print statements execute in order around the app call.Final Answer:
Before app printed before request, After app printed after request -> Option DQuick Check:
Middleware prints before and after app call [OK]
- Assuming only one print runs
- Thinking prints happen asynchronously
- Confusing middleware with Flask route handlers
class BrokenMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
# Forgot to call the wrapped app
return 'Hello'Solution
Step 1: Check middleware call method
The __call__ method must call the wrapped app with environ and start_response to get the response.Step 2: Identify missing call
This code returns a string directly and does not call the wrapped app, breaking the WSGI chain.Final Answer:
Middleware must call the wrapped app and return its response -> Option AQuick Check:
Middleware must call wrapped app [OK]
- Returning a string instead of calling app
- Removing __init__ method unnecessarily
- Misunderstanding WSGI call signature
X-Custom-Header: Hello to every response. Which approach correctly implements this?Solution
Step 1: Understand start_response role
start_response is a callable that sets HTTP status and headers before the response body is sent.Step 2: Add header by wrapping start_response
Middleware should wrap start_response to add the custom header before passing it to the app, so when the app calls it, the header is added.Final Answer:
Wrap the app and modify the start_response to add the header before calling the app -> Option BQuick Check:
Add headers by wrapping start_response before app call [OK]
- Adding headers after calling app (too late, start_response already called by app)
- Modifying response iterable directly (not standard for headers)
- Changing all routes instead of middleware
Ready to prove it?
Pass the test and this pattern moves unknown
