Performance: WSGI middleware concept
WSGI middleware affects server request handling speed and response time before the app processes requests.
def middleware(app): def new_app(environ, start_response): # lightweight logging, defer heavy work enqueue_log(environ) # async or buffered logging if not check_auth(environ): start_response('401 Unauthorized', [('Content-Type', 'text/plain')]) return [b'Unauthorized'] return app(environ, start_response) return new_app
def middleware(app): def new_app(environ, start_response): # heavy logging with blocking I/O log_request(environ) # synchronous file write if not check_auth(environ): start_response('401 Unauthorized', [('Content-Type', 'text/plain')]) return [b'Unauthorized'] return app(environ, start_response) return new_app
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous blocking middleware | 0 | 0 | 0 | [X] Bad |
| Asynchronous or lightweight middleware | 0 | 0 | 0 | [OK] Good |
MyMiddleware?app using app = MyMiddleware(app).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)class BrokenMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
# Forgot to call the wrapped app
return 'Hello'X-Custom-Header: Hello to every response. Which approach correctly implements this?Pass the test and this pattern moves unknown