Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a Flask middleware class that initializes with the app.
Flask
class CustomMiddleware: def __init__(self, [1]): self.app = app
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'request' instead of 'app' as the parameter.
Not accepting any parameter in __init__.
✗ Incorrect
The middleware class needs to accept the app as a parameter to wrap it.
2fill in blank
mediumComplete the code to make the middleware callable by Flask.
Flask
def __call__(self, [1], start_response): return self.app([1], start_response)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'request' instead of 'environ'.
Using 'self' as the first argument.
✗ Incorrect
The __call__ method of middleware receives the WSGI environment dictionary as the first argument.
3fill in blank
hardFix the error in the middleware call to pass the correct arguments.
Flask
def __call__(self, environ, [1]): return self.app(environ, start_response)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'response' or 'request' instead of 'start_response'.
Omitting the second argument.
✗ Incorrect
The second argument to __call__ is the start_response callable used by WSGI.
4fill in blank
hardFill both blanks to add a print statement before calling the app.
Flask
def __call__(self, [1], [2]): print("Middleware active") return self.app([1], [2])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'request' or 'response' instead of WSGI parameters.
Swapping the order of arguments.
✗ Incorrect
The __call__ method must accept environ and start_response to work correctly.
5fill in blank
hardFill all three blanks to wrap the Flask app with the middleware.
Flask
app = Flask(__name__) app.wsgi_app = [1](app.[2]) @app.route('/') def home(): return [3]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning middleware directly to app instead of app.wsgi_app.
Returning a function instead of a string in the route.
✗ Incorrect
We wrap the Flask app's wsgi_app with CustomMiddleware and return a string from the route.