utils.deprecation.MiddlewareMixin

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:

  1. Calls self.process_request(request) (if defined).
  2. Calls self.get_response(request) to get the response from later middleware and the view.
  3. Calls self.process_response(request, response) (if defined).
  4. 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:

  1. Under MIDDLEWARE_CLASSES, every middleware will always have its process_response method called, even if an earlier middleware short-circuited by returning a response from its process_request method. Under MIDDLEWARE, 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 in MIDDLEWARE will see the response.
  2. Under MIDDLEWARE_CLASSES, process_exception is applied to exceptions raised from a middleware process_request method. Under MIDDLEWARE, process_exception applies only to exceptions raised from the view (or from the render method of a TemplateResponse). Exceptions raised from a middleware are converted to the appropriate HTTP response and then passed to the next middleware.
  3. Under MIDDLEWARE_CLASSES, if a process_response method raises an exception, the process_response methods of all earlier middleware are skipped and a 500 Internal Server Error HTTP response is always returned (even if the exception raised was e.g. an Http404). Under MIDDLEWARE, 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.
doc_Django
2016-10-09 18:40:22
Comments
Leave a Comment

Please login to continue.