Bird
Raised Fist0
Flaskframework~10 mins

WSGI middleware concept in Flask - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a WSGI middleware class that wraps an app.

Flask
class SimpleMiddleware:
    def __init__(self, app):
        self.app = [1]

    def __call__(self, environ, start_response):
        return self.app(environ, start_response)
Drag options to blanks, or click blank then click option'
Aenviron
Bapp
Cstart_response
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning the wrong variable to self.app
Using environ or start_response instead of app
2fill in blank
medium

Complete the code to call the wrapped app inside the middleware __call__ method.

Flask
def __call__(self, environ, start_response):
    # Call the wrapped app
    return self.app([1], start_response)
Drag options to blanks, or click blank then click option'
Aenviron
Bself
Cstart_response
Dapp
Attempts:
3 left
💡 Hint
Common Mistakes
Passing self or start_response as the first argument
Swapping the order of arguments
3fill in blank
hard

Fix the error in the middleware call by completing the code to modify the response headers.

Flask
def __call__(self, environ, start_response):
    def custom_start(status, headers, exc_info=None):
        headers.append(('X-Custom', 'Middleware'))
        return start_response(status, headers, exc_info)

    return self.app(environ, [1])
Drag options to blanks, or click blank then click option'
Astart_response
Bself
Cenviron
Dcustom_start
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the original start_response instead of custom_start
Passing environ instead of a callable
4fill in blank
hard

Fill both blanks to create a middleware that logs the request path and then calls the app.

Flask
def __call__(self, environ, start_response):
    print('Request path:', environ[[1]])
    return self.app(environ, [2])
Drag options to blanks, or click blank then click option'
A'PATH_INFO'
Bstart_response
C'REQUEST_METHOD'
Dcustom_start
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'REQUEST_METHOD' instead of 'PATH_INFO' for the path
Passing custom_start when it is not defined
5fill in blank
hard

Fill all three blanks to create a middleware that adds a header and logs the method.

Flask
def __call__(self, environ, start_response):
    def [1](status, headers, exc_info=None):
        headers.append(('X-Added-By', 'Middleware'))
        return start_response(status, headers, exc_info)

    print('Method:', environ[[2]])
    return self.app(environ, [3])
Drag options to blanks, or click blank then click option'
Acustom_start
B'REQUEST_METHOD'
Dstart_response
Attempts:
3 left
💡 Hint
Common Mistakes
Using start_response instead of custom_start when calling the app
Using 'PATH_INFO' instead of 'REQUEST_METHOD' for the method

Practice

(1/5)
1. What is the main role of WSGI middleware in a Flask application?
easy
A. To serve static files directly to the client
B. To replace the Flask app entirely
C. To sit between the server and the Flask app to modify requests or responses
D. To handle database connections automatically

Solution

  1. Step 1: Understand WSGI middleware position

    WSGI middleware acts as a layer between the web server and the Flask app, intercepting requests and responses.
  2. Step 2: Identify middleware purpose

    It modifies or adds features like logging or security without replacing the app or handling unrelated tasks.
  3. Final Answer:

    To sit between the server and the Flask app to modify requests or responses -> Option C
  4. Quick Check:

    Middleware = intercepts requests/responses [OK]
Hint: Middleware wraps app to add features between server and app [OK]
Common Mistakes:
  • Thinking middleware replaces the app
  • Confusing middleware with static file serving
  • Assuming middleware manages database connections
2. Which of the following is the correct way to wrap a Flask app with WSGI middleware named MyMiddleware?
easy
A. app = MyMiddleware(app)
B. app = app.MyMiddleware()
C. MyMiddleware(app)
D. app.middleware = MyMiddleware

Solution

  1. Step 1: Recall middleware wrapping syntax

    WSGI middleware wraps the Flask app by passing the app instance to the middleware constructor.
  2. Step 2: Match correct syntax

    The correct syntax is assigning the wrapped app back to app using app = MyMiddleware(app).
  3. Final Answer:

    app = MyMiddleware(app) -> Option A
  4. Quick Check:

    Wrap app by passing it to middleware constructor [OK]
Hint: Wrap app by calling middleware with app as argument [OK]
Common Mistakes:
  • Calling middleware as a method on app
  • Not assigning wrapped app back to a variable
  • Assigning middleware class without instantiation
3. Given this WSGI middleware code wrapping a Flask app, what will be printed when a request is made?
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 = Flask(__name__)
app = SimpleMiddleware(app)
medium
A. No output is printed
B. Only Before app is printed
C. Only After app is printed
D. Before app printed before request, After app printed after request

Solution

  1. Step 1: Analyze middleware call flow

    The middleware prints 'Before app' before calling the wrapped app, then prints 'After app' after the app returns.
  2. Step 2: Understand request handling

    When a request comes, both print statements execute in order around the app call.
  3. Final Answer:

    Before app printed before request, After app printed after request -> Option D
  4. Quick Check:

    Middleware prints before and after app call [OK]
Hint: Middleware __call__ runs code before and after app call [OK]
Common Mistakes:
  • Assuming only one print runs
  • Thinking prints happen asynchronously
  • Confusing middleware with Flask route handlers
4. Identify the error in this WSGI middleware implementation:
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 call the wrapped app and return its response
B. Middleware should not have an __init__ method
C. Middleware should return a Flask response object, not a string
D. Middleware must not accept environ and start_response parameters

Solution

  1. Step 1: Check middleware call method

    The __call__ method must call the wrapped app with environ and start_response to get the response.
  2. Step 2: Identify missing call

    This code returns a string directly and does not call the wrapped app, breaking the WSGI chain.
  3. Final Answer:

    Middleware must call the wrapped app and return its response -> Option A
  4. Quick Check:

    Middleware must call wrapped app [OK]
Hint: Middleware must call and return wrapped app response [OK]
Common Mistakes:
  • Returning a string instead of calling app
  • Removing __init__ method unnecessarily
  • Misunderstanding WSGI call signature
5. You want to add a WSGI middleware to your Flask app that adds a custom header X-Custom-Header: Hello to every response. Which approach correctly implements this?
hard
A. Wrap the app and modify the start_response to add the header after calling the app
B. Wrap the app and modify the start_response to add the header before calling the app
C. Modify the Flask app routes to add the header manually in each view
D. Add the header in the middleware by modifying the response iterable directly without start_response

Solution

  1. Step 1: Understand start_response role

    start_response is a callable that sets HTTP status and headers before the response body is sent.
  2. Step 2: Add header by wrapping start_response

    Middleware should wrap start_response to add the custom header before passing it to the app, so when the app calls it, the header is added.
  3. Final Answer:

    Wrap the app and modify the start_response to add the header before calling the app -> Option B
  4. Quick Check:

    Add headers by wrapping start_response before app call [OK]
Hint: Wrap start_response to add headers before app call [OK]
Common Mistakes:
  • Adding headers after calling app (too late, start_response already called by app)
  • Modifying response iterable directly (not standard for headers)
  • Changing all routes instead of middleware
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