Creating a custom middleware

You already know the MIDDLEWARE setting, which contains the middlewares for your project. You can think of it as a low-level plugin system, allowing you to implement hooks that get executed in the request/response process. Each middleware is responsible for some specific action that will be executed for all HTTP requests or responses.

Avoid adding expensive processing to middlewares, since they are executed in every single request.

When an HTTP request is received, middlewares are executed in order of appearance in the MIDDLEWARE setting. When an HTTP response has been generated by Django, the response passes through all middlewares back in reverse order.

A middleware can be written as a function as follows:

def my_middleware(get_response):

def middleware(request):
# Code executed for each request before
# the view (and later middleware) are called.

response = get_response(request)

# Code executed for each request/response after
# the view is called.

return response

return middleware

A middleware factory is a callable that takes a get_response callable and returns a middleware. A middleware is a callable that takes a request and returns a response, just like a view. The get_response callable might be the next middleware in the chain or the actual view in case of the last listed middleware.

If any middleware returns a response without calling its get_response callable, it short-circuits the process, no further middlewares get executed (also not the view), and the response returns through the same layers that the request passed in through.

The order of middlewares in the MIDDLEWARE setting is very important because a middleware can depend on data set in the request by other middlewares that have been executed previously.

When adding a new middleware to the MIDDLEWARE setting, make sure to place it in the right position. Middlewares are executed in order of appearance in the setting during the request phase, and in reverse order for responses.

You can find more information about middleware at https://docs.djangoproject.com/en/2.0/topics/http/middleware/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset