Writing your own middleware

Writing your own middleware is easy. Each middleware component is a single Python class that defines one or more of the following methods:

process_request

Method: process_request(request)

  • request is an HttpRequest object.
  • process_request() is called on each request, before Django decides which view to execute.

It should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other process_request() middleware, then, process_view() middleware, and finally, the appropriate view.

If it returns an HttpResponse object, Django won't bother calling any other request, view or exception middleware, or the appropriate view; it'll apply response middleware to that ...

Get Mastering Django: Core now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.