Complete the code to define a WSGI middleware class that wraps an app.
class SimpleMiddleware: def __init__(self, app): self.app = [1] def __call__(self, environ, start_response): return self.app(environ, start_response)
The middleware stores the wrapped WSGI app in self.app. So the constructor must assign app to self.app.
Complete the code to call the wrapped app inside the middleware __call__ method.
def __call__(self, environ, start_response): # Call the wrapped app return self.app([1], start_response)
The WSGI app is called with the environ dictionary and the start_response callable.
Fix the error in the middleware call by completing the code to modify the response headers.
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])
The middleware replaces the start_response callable with custom_start to add headers before calling the original start_response.
Fill both blanks to create a middleware that logs the request path and then calls the app.
def __call__(self, environ, start_response): print('Request path:', environ[[1]]) return self.app(environ, [2])
The request path is in environ['PATH_INFO']. The middleware then calls the wrapped app with start_response.
Fill all three blanks to create a middleware that adds a header and logs the method.
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])
The middleware defines a custom_start function to add headers. It logs the HTTP method from environ['REQUEST_METHOD'] and calls the app with custom_start.