Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Creating a custom Django Middleware

Creating a custom Django Middleware

Basic tutorial to learn about Django middlewares and how to create one.

Andrea Grandi

October 06, 2015
Tweet

More Decks by Andrea Grandi

Other Decks in Programming

Transcript

  1. WHY YOU MAY WANT TO CREATE A MIDDLEWARE? • Passing

    more informations to the views or templates • Altering the data inside a request before it reaches the views/templates • Having a different behaviour in the views/templates, depending on certain conditions (ignoring requests from a particular IP address)
  2. THINGS TO KNOW WHEN YOU WRITE A MIDDLEWARE • You

    need to write a class that just inherits from object • The order in settings.py is important: middlewares are processed from top to bottom during a request and from bottom to top during a response. • You don’t need to implement all the available methods of a middleware. For example you can just implement process_request and process_template_response • If you implement process_request and you decide to return an HttpResponse, all the other middlewares, views etc… will be ignored and only your response will be returned
  3. AVAILABLE HOOKS • process_request(request) • process_view( request, view_func, view_args, view_kwargs)

    • process_exception(request, response) • process_template_response(request, response) • process_response(request, response) (during a request) (during a response)
  4. EXAMPLE: BENCHMARKMIDDLEWARE from datetime import datetime class BenchmarkMiddleware(object): def process_request(self,

    request): request._request_time = datetime.now() def process_template_response(self, request, response): response_time = datetime.now() - request._request_time response.context_data['response_time'] = response_time return response