How do I get the content length of a Django respon

2019-06-16 04:58发布

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?

2条回答
Rolldiameter
2楼-- · 2019-06-16 05:17

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.

查看更多
淡お忘
3楼-- · 2019-06-16 05:30

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.

查看更多
登录 后发表回答