How do I get the content length of a Django response object?

William picture William · Apr 5, 2011 · Viewed 11.2k times · Source

In Django, I try to logging the request and response content length, which exactly the same as what Django server prints to stderr.

[05/Apr/2011 22:59:08] "GET /pages/ HTTP/1.1" 200 332161
[05/Apr/2011 22:59:15] "GET /pages/12 HTTP/1.1" 301 0
[05/Apr/2011 22:59:15] "GET /pages/12/ HTTP/1.1" 200 361474
[05/Apr/2011 22:59:16] "GET /pages/12/load/tags/ HTTP/1.1" 200 13899
[05/Apr/2011 22:59:16] "GET /pages/12/load/comments/ HTTP/1.1" 200 82

So, I write a simple middleware as follows, but, the value of 'Content-Length' is always empty.

class LogHttpResponse(object):
    def process_response(self, request, response):
        import datetime  
        print response.items()
        time_text = datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S')
        print '[%s] "%s %s" %d %s' % (time_text, request.method, request.path, 
                                      response.status_code, 
                                      response.get('Content-Length', ''))
        return response 

I've checked through fire-debug, there is 'Content-Length' in the response headers. But there is no 'Content-Length' in the middleware, "print response.items()" shows:

[('Content-Type', 'text/html; charset=utf-8')]

Is there any problem of the middleware orders?

Answer

Torsten Engelbrecht picture Torsten Engelbrecht · Apr 6, 2011

I've checked through fire-debug, there is 'Content-Length' in the response headers. But there is no 'Content-Length' in the middleware [...] Is there any problem of the middleware orders?

Yes. Middleware classes are applied from top-down (in settings.MIDDLEWARE_CLASSES) when processing request and bottom-up when processing the response. If you have 'django.middleware.http.ConditionalGetMiddleware' in you middleware classes it will add a 'Content-Length' header to the HttpResponse.

Though if you put your middleware class after 'django.middleware.http.ConditionalGetMiddleware' in settings.MIDDLEWARE_CLASSES it will apply this one first when processing the response and then apply the ConditionalMiddleware afterwards. That's why you see a Content-Length header in Firebug, though its not yet processed when you Middleware is called.

See Django Middleware documentation for more information about Middleware's.