Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django middware only "process_response" when miss trailing slash

i've write a middware like this:

class LogMiddleware( object ):

    def process_request( self, request ):
        logging.debug("start")

    def process_response( self, request, response ):
        logging.debug("end")
        return response

and I put it in the bottom of MIDDLEWARE_CLASSES

most time it works fine.

and when I test with url /admin without an trailing "/" and I could only see the "end" logged, why?

like image 938
fallhunter Avatar asked Dec 06 '22 04:12

fallhunter


1 Answers

The documentation explains this.

Middleware classes are processed in the order they appear. The CommonMiddleware class is higher up than your LogMiddleware class, so is processed first. It performs a redirect because your URL doesn't end with a slash, so returns an HttpResponseRedirect.

If a request middleware returns a response, as in this case, no further request middleware classes are processed, so 'start' is not logged. However, response middleware classes are always processed, so 'end' is logged.

like image 63
Daniel Roseman Avatar answered Mar 06 '23 05:03

Daniel Roseman