DJANGO MIDDLEWARE
Creating a custom
@andreagrandi
Andrea Grandi
DJANGO ARCHITECTURE
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)
THINGS TO KNOW WHEN YOU WRITE A MIDDLEWARE
• You need to write a class that just inherit 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
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 = request._request_time - datetime.now() response.context_data['response_time'] = abs(response_time) return response
REFERENCES
Complete example:
https://github.com/andreagrandi/benchmark-middleware-example
Documentation:
• https://docs.djangoproject.com/en/1.8/topics/http/middleware/• http://agiliq.com/blog/2015/07/understanding-django-middlewares/• http://code.runnable.com/UrSGolK00ygpAAAQ/creating-a-custom-
middleware-for-python-and-django
Thanks!
Top Related