So there's two methods which apply to what you're talking about in middleware.
You have process_request
and then process_response
.
As you make a request, django goes through the middleware from the top, to the bottom calling process_request
. Then it hits the view, and on the way back with the response the middleware is processed from the bottom to the top, calling process_response
.
Specific to your examples with cache, FetchFromCacheMiddleware
contains process_request
and UpdateCacheMiddleware
contains process_response
.
To quote the docs...
Middleware order and layering
During the request phase, before calling the view, Django applies middleware in the order it’s defined in MIDDLEWARE, top-down.
You can think of it like an onion: each middleware class is a "layer" that wraps the view, which is in the core of the onion. If the request passes through all the layers of the onion (each one calls get_response
to pass the request in to the next layer), all the way to the view at the core, the response will then pass through every layer (in reverse order) on the way back out.
If one of the layers decides to short-circuit and return a response without ever calling its get_response
, none of the layers of the onion inside that layer (including the view) will see the request or the response. The response will only return through the same layers that the request passed in through.
The docs are here; https://docs.djangoproject.com/en/3.1/topics/http/middleware/#middleware-order-and-layering