开发者

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

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?


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.


How about len(response.content)? That’d give you the number of characters in the response’s content. I guess that isn’t necessarily the same as the number of bytes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜