1.

What is the usage of middlewares in Django?

Answer»

DJANGO middleware is a framework of hooks to MODIFY request and response objects. 

If you want to modify the HTTPREQUEST object which is sent to the view, or you want to modify the HttpResponse object returned from the view, you can use middleware.

Django provides some default middleware like AuthenticationMiddleware.

Middleware is used in a number of key pieces of functionality in the Django project and you can use CSRF MIDDLEWARES to prevent cross-site request forgery attacks or to handle session data. With the use of middleware Authentication and authorization can be accomplished. To shape the flow of data through the application, you can write your own middleware classes.

One of the following methods must have in Django middleware.

process_request, process_response, process_view and process_exception.

These methods will be collected by WSGI Handler and called in the listed order.

Before any view executes, Django WANTS user attribute to be sent on request and to accomplish this Django takes a middleware approach. So AuthenticationMiddleware can modify the request object like -

https://github.com/django/django/blob/master/django/contrib/auth/middleware.py#L22

The same way to show the user's timezone on the page of the user, you can access the user's timezone in all views. You can use TimezoneMiddleware.

  • class TimezoneMiddleware(object):   
  • def process_request(self, request):         
  • # Assuming user has a OneToOneField to a model called Profile         
  • # And Profile stores the timezone of the User.         
  • request.session['timezone'] = request.user.profile.timezone

TimezoneMiddleware is dependent on request.user and request.user is populated in AuthenticationMiddleware. So timezone middleware written must come after AuthenticationMiddleware in the tuple settings.MIDDLEWARE_CLASSES.



Discussion

No Comment Found