[PYTHON] Django Middleware Execution Order

I was wondering in what order the code would be executed if I specified multiple Middleware in Django, so I tried it.

Experimental code

settings.py Excerpt from the configuration file

    #・ ・ ・ ・ Various Middleware,

middleware.py Define two middleware

class Middleware1:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print("M1 before")
        response = self.get_response(request)
        print("M1 after")

        return response

class Middleware2:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print("M2 before")
        response = self.get_response(request)
        print("M2 after")

        return response

hoge.py Textile View

from django.http import HttpResponse
from django.views import View

class Hoge(View):
    def get(self, request):
        return HttpResponse()

Experimental result

The result of requesting the endpoint corresponding to Hoge View

M1 before
M2 before
M2 after
M1 after

--__call__ is executed in a nested manner in the order of Middleware defined in the configuration file. --View code is executed only once in the middle of nesting.

After writing, I noticed [this article](https://qiita.com/shirakiya/items/1503eaffe81f91af5b9d#middleware%E3%82%92%E5%88%A9%E7%94%A8%E3% 81% 99% E3% 82% 8B% E8% A8% AD% E5% AE% 9A% E3% 82% 92% E8% BF% BD% E5% 8A% A0% E3% 81% 99% E3% 82% 8B) also had the following description showing the same fact.

Also, when the request is sent, Middleware will execute the process described in (2) in order from the top of the settings in this settings.py. On the other hand, the processes described in (3) are executed in the reverse order. Therefore, in some cases, it is necessary to be aware of this order when setting.

(I understand how it's nested, so it's okay ...)

Recommended Posts

Django Middleware Execution Order
Create your own Django middleware
(Note) Template file search order in Django
Python execution server construction (Python + uWSGI + Django + Nginx)
I made CORS custom middleware with Django
Django: Test Middleware that depends on another Middleware