[Answered ]-Django: how middleware know something to execute before view is called and something after view is called

1👍

get_response is a reference to a function. That function is the underlying middleware, or for the deepest middleware eventually a function that will look to the URL patterns, extract the parameters and call the corresponding view.

Indeed, imagine that f is a function:

def f(request):
    return HttpResponse('foobar')

then we can "wrap" that function ino the middleware with:

wrapped_view = simple_middleware(f)

We thus pass it a reference to our very simple view. If we then invoke the wrapped view with:

wrapped_view(some_request)

Then Python will first execute the code before the response = get_response(request) line, then call the get_response(request) function, which will thus trigger f, and then it can process the response.

Django here thus for middleware implements a decorator pattern [wiki].

Middleware does not per se needs to run the underlying function, or it can even run it multiple times. We can for example implement middleware that will only call the underlying function if a certain cookie is set:

def my_middleware(get_response):
    def middleware(request):
        if 'MY_COOKIE' in request.COOKIES:
            return get_response(request)
        else:
            return HttpResponse('Cookie needs to be set!', status=400)

in that case it is thus conditional to call the underlying function.

Leave a comment