繁体   English   中英

如何获取Django响应对象的内容长度?

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

在Django中,我尝试记录请求和响应内容长度,这与Django服务器打印到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

所以,我写了一个简单的中间件如下,但是,'Content-Length'的值总是空的。

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 

我通过fire-debug检查过, 响应头中有'Content-Length' 但是中间件中没有“内容长度”,“print response.items()”显示:

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

中间件订单有什么问题吗?

我通过fire-debug检查过,响应头中有'Content-Length'。 但是中间件中没有“内容长度”[...]中间件订单是否有任何问题?

是。 中间件类在处理请求时自上而下(在settings.MIDDLEWARE_CLASSES )应用,在处理响应时自下而上。 如果你的中间件类中有'django.middleware.http.ConditionalGetMiddleware' ,它会在HttpResponse中添加一个'Content-Length'标题。

虽然如果你把你的中间件类放在settings.MIDDLEWARE_CLASSES 'django.middleware.http.ConditionalGetMiddleware' ,它会在处理响应时先应用这个,然后再应用ConditionalMiddleware 这就是为什么你在Firebug中看到Content-Length标头的原因,尽管在调用Middleware时它尚未处理。

有关Middleware的更多信息,请参阅Django Middleware文档

len(response.content)怎么样? 这会给你回复内容中的字符数。 我猜这不一定与字节数相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM