Bird
Raised Fist0
Flaskframework~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of creating custom middleware in a Flask application?
easy
A. To run code before and after each request is processed by Flask
B. To define new routes and views in the Flask app
C. To replace Flask's built-in request handling completely
D. To create database models for the application

Solution

  1. Step 1: Understand middleware role

    Middleware runs code around request processing, before and after Flask handles requests.
  2. Step 2: Compare options

    Only To run code before and after each request is processed by Flask describes this behavior. Other options describe unrelated tasks.
  3. Final Answer:

    To run code before and after each request is processed by Flask -> Option A
  4. Quick Check:

    Middleware purpose = run code around requests [OK]
Hint: Middleware wraps requests to add extra processing [OK]
Common Mistakes:
  • Confusing middleware with route creation
  • Thinking middleware replaces Flask core
  • Mixing middleware with database models
2. Which of the following is the correct way to define a custom middleware class in Flask?
easy
A. class MyMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): return self.app(environ, start_response)
B. def MyMiddleware(app): return app
C. class MyMiddleware: def handle_request(self): pass
D. class MyMiddleware: def __init__(self): pass

Solution

  1. Step 1: Check middleware class structure

    Middleware must accept the app in __init__ and implement __call__ with environ and start_response.
  2. Step 2: Validate options

    Only class MyMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): return self.app(environ, start_response) matches this pattern correctly. Others miss __call__ or parameters.
  3. Final Answer:

    Correct middleware class with __init__ and __call__ methods -> Option A
  4. Quick Check:

    Middleware class needs __call__ method [OK]
Hint: Middleware class must implement __call__(environ, start_response) [OK]
Common Mistakes:
  • Omitting __call__ method
  • Not passing app to __init__
  • Using function instead of class
3. Given this middleware code, what will be printed when a request is made?
class LoggerMiddleware:
    def __init__(self, app):
        self.app = app
    def __call__(self, environ, start_response):
        print('Before request')
        response = self.app(environ, start_response)
        print('After request')
        return response

app.wsgi_app = LoggerMiddleware(app.wsgi_app)
medium
A. Only After request printed
B. Only Before request printed
C. No output printed
D. Before request printed, then After request printed

Solution

  1. Step 1: Analyze __call__ method

    Prints 'Before request', calls app, then prints 'After request'.
  2. Step 2: Understand call order

    Both prints happen on each request, before and after app call.
  3. Final Answer:

    Before request printed, then After request printed -> Option D
  4. Quick Check:

    Prints before and after app call [OK]
Hint: Middleware __call__ runs code before and after app call [OK]
Common Mistakes:
  • Thinking only one print runs
  • Confusing order of prints
  • Assuming prints happen outside __call__
4. Identify the error in this middleware code snippet:
class BadMiddleware:
    def __init__(self, app):
        self.app = app
    def __call__(self, request):
        print('Middleware active')
        return self.app(request)
medium
A. Missing __init__ method to accept app
B. __call__ method has wrong parameters; should be (environ, start_response)
C. Middleware class should not print anything
D. The return statement should be outside __call__

Solution

  1. Step 1: Check __call__ method signature

    WSGI middleware __call__ must accept (environ, start_response), not (request).
  2. Step 2: Validate other parts

    __init__ is correct, printing is allowed, return inside __call__ is correct.
  3. Final Answer:

    __call__ method has wrong parameters; should be (environ, start_response) -> Option B
  4. Quick Check:

    Middleware __call__ signature = (environ, start_response) [OK]
Hint: Middleware __call__ needs environ and start_response params [OK]
Common Mistakes:
  • Using Flask request object instead of WSGI params
  • Omitting start_response parameter
  • Misplacing return statement
5. You want to create middleware that adds a custom header 'X-Hello: World' to every response. Which code snippet correctly implements this?
hard
A. class HeaderMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): response = self.app(environ, start_response) response.headers['X-Hello'] = 'World' return response
B. class HeaderMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): start_response('200 OK', [('X-Hello', 'World')]) return self.app(environ, start_response)
C. 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-Hello', 'World')) return start_response(status, headers, exc_info) return self.app(environ, custom_start_response)
D. class HeaderMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): environ['X-Hello'] = 'World' return self.app(environ, start_response)

Solution

  1. Step 1: Understand WSGI header modification

    Headers are set by calling start_response with status and headers. To add headers, wrap start_response.
  2. Step 2: Check options for correct header addition

    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-Hello', 'World')) return start_response(status, headers, exc_info) return self.app(environ, custom_start_response) wraps start_response to append header before calling original start_response. Others misuse start_response or response object.
  3. Final Answer:

    Wrap start_response to add header before calling original -> Option C
  4. Quick Check:

    Add headers by wrapping start_response [OK]
Hint: Wrap start_response to add headers in middleware [OK]
Common Mistakes:
  • Calling start_response twice incorrectly
  • Trying to modify response object directly in WSGI
  • Adding headers to environ instead of response
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard