Django middleware

In the django project settings there is a key called MIDDLEWARE_CLASSES which is a tuple of strings implementing the middleware methods. Django base handler (TBD explain what this class does) reads this setting and initializes three of its own attributes: _request_middleware, _view_middleware and _response_middleware. It goes through the list of middleware classes instantiates each of them and adds the bound method process_request to the _request_middleware attribute, process_view method to view_middleware and process_reponse method to _response middleware.

If the middleware class method returns something (indicating that it has taken some action), the basehandler get_response method returns immediately. Otherwise it proceeds further.

There are 4 middleware classes built in:

  • AdminUserRequired middleware class implements the process_view method and silently returns if the user in the request is logged in and is a valid admin user. Otherwise it returns login page with appropriate error message.
  • CommonMiddleware implements process_view and process_response methods. process_view rejects forbidden user-agents and prepends URL with www and appends trailing slash if desired. process_response checks if there is a matching flat file present that can be sent for 404's and can also send email note to managers about broken links. process_response also manages ETags
  • CacheMiddleware implements process_request to check pages (not containing any query string) against cache. process_response adds pages to cache as needed.
  • XViewMiddleware (used internally for documentation) implements process_view and attaches 'X-View' header to internal HEAD requests.

Update: 10/14/2005. There are some updates to the middleware that ships with django and is now "officially" documented here.

Leave a Reply