What is middleware in django?
Middleware :
- Middleware is a framework of hooks into Django’s request/response processing.
- Middleware is a lightweight plugin for Django.
- It allows modifying request or response or the view parameters.
- Each middleware component is responsible for doing some specific function. For example, Django includes a middleware component, AuthenticationMiddleware, that associates users with requests using sessions.
- When to use middleware :
- We can use middleware if you want to modify the request i.e HttpRequest object which is sent to the view. Or you might want to modify the HttpResponse object returned from the view. Both these can be achieved by using middleware.
- We might want to perform an operation before the view executes. In such case, we would use a middleware.
- Hooks and Application order :
- Request phase :
- During the request phase, before calling the view. Django applies middleware in the order it's defined in MIDDLE_CLASSES top-down.
- 2 hooks are available :
- process_request() is called on each request before Django decides which view to execute.
- process_view() is called just before Django calls the view.
- Response phase :
- During the response phase, after calling the view, middlewares are applied in reverse order from the bottom up.
- 3 hooks are available :
- process_exception() :
- It is called only if the view raised an exception
- process_template_response() :
- It is called only for template responses
- process_response() :
- It is called on all responses before they are returned to the browser.
- It must return a HttpResponse or StreamingHttpResponse.
Comments
Post a Comment