📖 Scenario: You are building a simple Flask web app that logs every request's path before processing it. Middleware helps add this logging without changing the main app code.
🎯 Goal: Create a Flask app and add middleware that logs the request path for every incoming request, showing how middleware extends app functionality.
📋 What You'll Learn
Create a Flask app instance named app
Define a middleware function named log_middleware that logs the request path
Apply the middleware to the Flask app using app.wsgi_app
Create a route /hello that returns 'Hello, World!'
💡 Why This Matters
🌍 Real World
Middleware is used in real web apps to add features like logging, authentication, or error handling without changing core app code.
💼 Career
Understanding middleware helps developers build scalable and maintainable web applications by cleanly extending functionality.
Progress0 / 4 steps
1
Create the Flask app instance
Create a Flask app instance called app by importing Flask from flask and initializing it with Flask(__name__).
Flask
Hint
Use app = Flask(__name__) to create the app instance.
2
Define the middleware function
Define a middleware function named log_middleware that takes environ and start_response as parameters. Inside, print the request path from environ['PATH_INFO'], then call the next app in the chain with app.wsgi_app(environ, start_response) and return its result.
Flask
Hint
Middleware functions take environ and start_response, print the path, then call app.wsgi_app.
3
Apply the middleware to the Flask app
Assign the middleware function log_middleware to app.wsgi_app so it wraps the original app. Use app.wsgi_app = log_middleware.
Flask
Hint
Save the original app.wsgi_app before wrapping it, then assign log_middleware to app.wsgi_app.
4
Add a route to test the middleware
Create a route /hello using @app.route('/hello') that returns the string 'Hello, World!'.
Flask
Hint
Use @app.route('/hello') to define the route and a function that returns the greeting.
Practice
(1/5)
1. What is the main purpose of middleware in a Flask application?
easy
A. To add extra processing steps before or after the main app handles a request
B. To replace the Flask app's routing system
C. To directly modify the database schema
D. To serve static files like images and CSS
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 A
Quick Check:
Middleware extends app functionality = C [OK]
Hint: Middleware adds steps around app requests and responses [OK]
Common Mistakes:
Thinking middleware replaces routing
Confusing middleware with static file serving
Assuming middleware changes database structure
2. Which of the following is the correct way to add middleware in a Flask app?
easy
A. app = Middleware(app)
B. app.middleware = Middleware()
C. Middleware(app).run()
D. app.add_middleware(Middleware)
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 A
Quick Check:
Middleware wraps app instance = A [OK]
Hint: Middleware wraps app like a gift box around it [OK]
Common Mistakes:
Trying to assign middleware as an attribute
Calling run() on middleware instead of app
Using non-existent add_middleware method
3. Given this middleware code, what will be printed when a request is made?
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 D
Quick Check:
Middleware prints before and after app = A [OK]
Hint: Middleware prints before and after calling app [OK]
Common Mistakes:
Thinking only one print runs
Assuming prints happen in reverse order
Forgetting __call__ runs on each request
4. This middleware code causes an error. What is the problem?
class BrokenMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
# Forgot to call the wrapped app
return 'Hello'
medium
A. Middleware must return a number, not a string
B. Middleware must call the wrapped app to return a valid response
C. Middleware should not have a __call__ method
D. Middleware __init__ method is missing
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 B
Quick Check:
Middleware must call app = D [OK]
Hint: Middleware must call wrapped app to work properly [OK]
Common Mistakes:
Returning a string instead of calling app
Missing __call__ method entirely
Thinking middleware returns numbers
5. You want to add middleware that logs request paths and modifies the response to add a custom header. Which approach correctly extends functionality using middleware?
hard
A. Modify the Flask app routes to log and add headers directly inside each route function
B. Use middleware that only logs requests but does not call the app
C. Create middleware that logs environ['PATH_INFO'], calls the app, then adds header to response before returning
D. Add a middleware that replaces the response with a fixed string ignoring the app
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 logs environ['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 logs environ['PATH_INFO'], calls the app, then adds header to response before returning -> Option C
Quick Check:
Middleware logs and modifies response = B [OK]
Hint: Middleware wraps app: log before, modify response after [OK]
Common Mistakes:
Modifying routes instead of middleware
Not calling the wrapped app
Replacing response ignoring app output
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.