Performance: Custom middleware creation
This affects the request-response cycle speed and server processing time, impacting how fast the server can respond to user requests.
from flask import Flask, request app = Flask(__name__) @app.before_request def fast_middleware(): # Quick check without blocking if 'X-Special-Header' not in request.headers: pass # Minimal processing @app.route('/') def index(): return 'Hello World!'
from flask import Flask, request app = Flask(__name__) @app.before_request def slow_middleware(): import time time.sleep(2) # Simulate slow processing @app.route('/') def index(): return 'Hello World!'
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking middleware with sleep | 0 | 0 | 0 | [X] Bad |
| Lightweight middleware with quick checks | 0 | 0 | 0 | [OK] Good |
class LoggerMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
print('Before request')
response = self.app(environ, start_response)
print('After request')
return response
app.wsgi_app = LoggerMiddleware(app.wsgi_app)class BadMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, request):
print('Middleware active')
return self.app(request)Pass the test and this pattern moves unknown