Performance: Why middleware extends functionality
Middleware affects request processing time and can impact server response speed and resource usage.
from flask import Flask, g app = Flask(__name__) @app.before_request def fast_middleware(): g.start_time = 123 # Quick setup without delay @app.route('/') def index(): return 'Hello World!'
from flask import Flask app = Flask(__name__) @app.before_request def slow_middleware(): import time time.sleep(1) # Simulate slow processing @app.route('/') def index(): return 'Hello World!'
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Middleware with blocking delay | N/A (server-side) | N/A | N/A | [X] Bad |
| Lightweight, fast middleware | N/A (server-side) | N/A | N/A | [OK] Good |
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 = 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'environ['PATH_INFO'], calls the app, then adds header to response before returning correctly logs the request path, calls the app, then modifies the response headers. Others either bypass app or do tasks incorrectly.environ['PATH_INFO'], calls the app, then adds header to response before returning -> Option CPass the test and this pattern moves unknown