1

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?

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

ah, wow ok, that makes sense ... that's why its called get_response() ... now I get it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.