0
0
Flaskframework~10 mins

Custom middleware creation in Flask - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Custom middleware creation
Request comes in
Middleware processes request
Pass request to Flask app
Flask app processes request
Response generated
Middleware processes response
Response sent back to client
Middleware intercepts requests before Flask handles them and can modify requests or responses.
Execution Sample
Flask
from flask import Flask, request

class SimpleMiddleware:
    def __init__(self, app):
        self.app = app
    def __call__(self, environ, start_response):
        print('Middleware before app')
        return self.app(environ, start_response)
This code defines a simple middleware class that prints a message before passing the request to the Flask app.
Execution Table
StepActionMiddleware OutputFlask App OutputResult
1Request received by middlewarePrints 'Middleware before app'Request passed to app
2Flask app processes requestGenerates response 'Hello World!'Response created
3Middleware receives responseCan modify response (not shown here)Response sent to client
4Request cycle endsResponse delivered to client
💡 Request processed and response sent back to client
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
environRequest environment dictPassed unchangedPassed unchangedPassed unchangedUsed to build response
start_responseCallable to start responsePassed unchangedPassed unchangedPassed unchangedCalled to send response
responseNoneNoneResponse object createdPossibly modifiedSent to client
Key Moments - 2 Insights
Why does middleware need to call the Flask app inside __call__?
Because middleware wraps the app, it must call the app with environ and start_response to let Flask handle the request, as shown in execution_table step 1.
Can middleware modify the response before sending it back?
Yes, middleware can modify the response after the app returns it, as indicated in execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what does the middleware print when a request is received?
AMiddleware before app
BFlask app started
CResponse generated
DRequest ended
💡 Hint
Check execution_table row 1 under Middleware Output
At which step does the Flask app generate the response?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at execution_table row 2 under Flask App Output
If middleware did not call the Flask app, what would happen?
ARequest would be processed normally
BRequest would not reach the Flask app and no response would be generated
CMiddleware would generate the response automatically
DResponse would be sent twice
💡 Hint
Refer to key_moments about why middleware must call the app
Concept Snapshot
Custom middleware wraps the Flask app.
It intercepts requests and responses.
Middleware __call__ method receives environ and start_response.
Middleware must call the app to continue processing.
Can modify request or response.
Useful for logging, auth, or headers.
Full Transcript
Custom middleware in Flask is a way to intercept requests before they reach the app and responses before they go back to the client. The middleware is a class with a __call__ method that receives the request environment and a start_response callable. It can do things like print messages or modify data. The middleware must call the Flask app inside __call__ to let the app process the request and generate a response. After the app returns, middleware can also modify the response before sending it back. This flow ensures middleware can add features like logging or authentication without changing the app code.