Middleware helps add extra features to your web app without changing its main code. It acts like a helper that works between the user and your app.
Why middleware extends functionality in Flask
from flask import Flask, request app = Flask(__name__) @app.before_request def middleware_function(): # Code here runs before each request pass @app.after_request def after_middleware(response): # Code here runs after each request return response
@app.before_request runs code before each request reaches your route.
@app.after_request runs code after your route sends a response.
from flask import Flask, request app = Flask(__name__) @app.before_request def check_auth(): if not request.headers.get('Authorization'): return 'Unauthorized', 401
from flask import Flask app = Flask(__name__) @app.after_request def add_header(response): response.headers['X-Custom-Header'] = 'Hello' return response
This simple Flask app uses middleware to print the path of every request before showing the homepage.
from flask import Flask, request app = Flask(__name__) @app.before_request def log_request(): print(f"Request to {request.path}") @app.route('/') def home(): return 'Welcome to the homepage!' if __name__ == '__main__': app.run(debug=True)
Middleware runs for every request, so keep it fast and simple.
Use middleware to keep your main code clean and focused on core tasks.
Flask middleware can stop a request early by returning a response inside before_request.
Middleware adds extra steps before or after your main app code runs.
It helps with tasks like security, logging, and modifying requests or responses.
Using middleware keeps your app organized and easier to maintain.
Practice
Solution
Step 1: Understand middleware role
Middleware acts as a layer that processes requests or responses around the main app logic.Step 2: Compare options
Replacing routing, modifying database schema, or serving static files are not middleware tasks.Final Answer:
To add extra processing steps before or after the main app handles a request -> Option AQuick Check:
Middleware extends app functionality = C [OK]
- Thinking middleware replaces routing
- Confusing middleware with static file serving
- Assuming middleware changes database structure
Solution
Step 1: Recall Flask middleware pattern
Middleware wraps the Flask app by passing the app instance to the middleware constructor.Step 2: Analyze options
Only app = Middleware(app) correctly wraps the app instance. Others use invalid syntax or methods not in Flask.Final Answer:
app = Middleware(app) -> Option AQuick Check:
Middleware wraps app instance = A [OK]
- Trying to assign middleware as an attribute
- Calling run() on middleware instead of app
- Using non-existent add_middleware method
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 = SimpleMiddleware(app)Solution
Step 1: Understand __call__ method flow
When a request comes, 'Before app' prints, then the wrapped app runs, then 'After app' prints.Step 2: Confirm both prints execute
Both print statements are before and after calling the app, so both appear in order.Final Answer:
Before app printed, then After app printed -> Option DQuick Check:
Middleware prints before and after app = A [OK]
- Thinking only one print runs
- Assuming prints happen in reverse order
- Forgetting __call__ runs on each request
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 __call__ method behavior
The middleware returns a string directly without calling the wrapped app, breaking the request flow.Step 2: Understand Flask middleware contract
Middleware must call the wrapped app to get a valid response object, then return it.Final Answer:
Middleware must call the wrapped app to return a valid response -> Option BQuick Check:
Middleware must call app = D [OK]
- Returning a string instead of calling app
- Missing __call__ method entirely
- Thinking middleware returns numbers
Solution
Step 1: Understand middleware responsibilities
Middleware should handle logging before calling the app and modify the response after.Step 2: Evaluate options
Create middleware that logsenviron['PATH_INFO'], calls the app, then adds header to response before returning correctly logs the request path, calls the app, then modifies the response headers. Others either bypass app or do tasks incorrectly.Final Answer:
Create middleware that logsenviron['PATH_INFO'], calls the app, then adds header to response before returning -> Option CQuick Check:
Middleware logs and modifies response = B [OK]
- Modifying routes instead of middleware
- Not calling the wrapped app
- Replacing response ignoring app output
Ready to prove it?
Pass the test and this pattern moves unknown
