Xen_mar
Xen_mar

Reputation: 9682

Implement Django middleware for response behaviour

I'm a bit confused by the middleware description in the official django docs and can't seem to wrap my head around it.

When implementing class-based middleware it looks something like this (ex. from docs):

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

    def __call__(self, request):
        response = self.get_response(request)
        return response

The middleware gets called for requests as well as for response. This is my first question:

How do I implement different behavior depending on if I'm processing a request or a response?

Also, and this is related, I'm a bit confused because there also seems to be an old deprecated way of writing middleware where it was possible to overwrite the methods process.request() and process_response(). I'm not sure if this way of writing middleware is inadvisable now. Usually, the Django docs are spot on but this part is a little confusing (to me).

Can someone clear this up for me?

Upvotes: 1

Views: 941

Answers (1)

ruddra
ruddra

Reputation: 51978

Basically the codes before responses = self.get_response(request) should process the request. self.get_response() will get the response from view, then codes after that should process the response. Finally you need to return the response from the function. Here is a visualization:

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

    def __call__(self, request):
        # Codes here will process the request
        # -----------------------------------
        response = self.get_response(request)
        # -----------------------------------
        # Codes here will process the response
        return response

Upvotes: 4

Related Questions