0
0
Flaskframework~30 mins

WSGI middleware concept in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
WSGI Middleware Concept with Flask
📖 Scenario: You are building a simple Flask web app that shows a greeting message. You want to add a WSGI middleware that logs each request path before the app handles it.
🎯 Goal: Create a Flask app and a WSGI middleware that logs the request path. The middleware should wrap the Flask app and print the path of every incoming request.
📋 What You'll Learn
Create a Flask app with one route '/' that returns 'Hello, World!'
Create a WSGI middleware class called LogMiddleware
The middleware should print the request path from the environ dictionary
Wrap the Flask app with the LogMiddleware before running
💡 Why This Matters
🌍 Real World
WSGI middleware is used in real web apps to add features like logging, authentication, or response modification without changing the main app code.
💼 Career
Understanding WSGI middleware helps backend developers customize and extend Python web apps efficiently, a valuable skill in web development jobs.
Progress0 / 4 steps
1
Create a basic Flask app
Create a Flask app called app with one route '/' that returns the string 'Hello, World!'.
Flask
Need a hint?

Use Flask(__name__) to create the app and @app.route('/') to define the route.

2
Create the WSGI middleware class
Create a WSGI middleware class called LogMiddleware with an __init__ method that takes app and stores it. Add a __call__ method that takes environ and start_response parameters.
Flask
Need a hint?

The middleware class needs to store the app and define a callable method.

3
Add logging of request path in middleware
Inside the __call__ method of LogMiddleware, print the request path from environ['PATH_INFO']. Then call the wrapped app with self.app(environ, start_response) and return its result.
Flask
Need a hint?

Use environ['PATH_INFO'] to get the path and print it before calling the app.

4
Wrap the Flask app with the middleware
Wrap the Flask app app with the LogMiddleware by assigning app = LogMiddleware(app) before running the app.
Flask
Need a hint?

Assign app = LogMiddleware(app) to wrap the Flask app.