Request and Response Processor
Django provides something called middlewares. These middlewares operate on the request and response objects and not on the WSGI layer like WSGI middlewares do. The advantage is that they can use the existing request and response objects and that the usage is much simpler. The following snippet shows how you can get a similar system in a werkzeug WSGI application:
from werkzeug import BaseRequest, BaseResponse class Middleware(object): def process_request(self, request): pass def process_response(self, request, response): return response # list of `Middleware` subclasses middlewares = [...] def application(environ, start_response): request = BaseRequest(environ) response = None for middleware in middlewares: response = middleware.process_request(request) if response is not None: break # dispatching code that creates a response object goes here if response is None: response = ... for middleware in reversed(middlewares): response = middleware.process_response(request, response) return response(environ, start_response)
One can also extend this concept and allow process_response to return a response object or add a process_exception method that is called when an unhandled exception is caught.