Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default list of Django built-in middleware

Django comes with a list of built-in middleware, but if one wants to use all (or most) of them, he has to work through tons of docs in order to get the right sorting in the settings.py file.

Is there an optimal default order of all built-in Django 1.1 middleware classes? I.e., something to copy'n'paste into settings.py:

MIDDLEWARE_CLASSES = (
  # perfect order here please ;-)
)

Alternative answer: Are there multiple possible orderings and what would be the difference?

By the way: The order is significant, but I'm only aware of some of the default dependencies, like SessionMiddleware before AuthenticationMiddleware.

like image 904
Boldewyn Avatar asked Dec 29 '22 09:12

Boldewyn


1 Answers

They do have a default list for the core Django middleware:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
)

Any other ones that you create or get from third parties can be added at the end of the tuple above. The Django book also mentions that on a view request, the order is from CommonMiddleware to AuthenticationMiddleware and finally to your view. On a return response, the order is reversed from AuthenticationMiddleware to CommonMiddleware. Here's the doc for it.

In response to the comment:

After scouring the Django tickets, it looks like this has been a know issue with the Django dev community and I don't think there is a final answer to it yet. Here's the ticket which contains the discussion along with the part where Jacob closed it down. You might want to try to bring that issue again as a Django ticket to get an official dev response.

like image 88
Thierry Lam Avatar answered Jan 17 '23 06:01

Thierry Lam