class django.utils.deprecation.MiddlewareMixin
Django provides django.utils.deprecation.MiddlewareMixin to ease creating middleware classes that are compatible with both MIDDLEWARE and the old MIDDLEWARE_CLASSES. All middleware classes included with Django are compatible with both settings.
The mixin provides an __init__() method that accepts an optional get_response argument and stores it in self.get_response.
The __call__() method:
- Calls
self.process_request(request)(if defined). - Calls
self.get_response(request)to get the response from later middleware and the view. - Calls
self.process_response(request, response)(if defined). - Returns the response.
If used with MIDDLEWARE_CLASSES, the __call__() method will never be used; Django calls process_request() and process_response() directly.
In most cases, inheriting from this mixin will be sufficient to make an old-style middleware compatible with the new system with sufficient backwards-compatibility. The new short-circuiting semantics will be harmless or even beneficial to the existing middleware. In a few cases, a middleware class may need some changes to adjust to the new semantics.
These are the behavioral differences between using MIDDLEWARE and MIDDLEWARE_CLASSES:
- Under
MIDDLEWARE_CLASSES, every middleware will always have itsprocess_responsemethod called, even if an earlier middleware short-circuited by returning a response from itsprocess_requestmethod. UnderMIDDLEWARE, middleware behaves more like an onion: the layers that a response goes through on the way out are the same layers that saw the request on the way in. If a middleware short-circuits, only that middleware and the ones before it inMIDDLEWAREwill see the response. - Under
MIDDLEWARE_CLASSES,process_exceptionis applied to exceptions raised from a middlewareprocess_requestmethod. UnderMIDDLEWARE,process_exceptionapplies only to exceptions raised from the view (or from therendermethod of aTemplateResponse). Exceptions raised from a middleware are converted to the appropriate HTTP response and then passed to the next middleware. - Under
MIDDLEWARE_CLASSES, if aprocess_responsemethod raises an exception, theprocess_responsemethods of all earlier middleware are skipped and a500 Internal Server ErrorHTTP response is always returned (even if the exception raised was e.g. anHttp404). UnderMIDDLEWARE, an exception raised from a middleware will immediately be converted to the appropriate HTTP response, and then the next middleware in line will see that response. Middleware are never skipped due to a middleware raising an exception.
Please login to continue.