如何获取Django响应对象的内容长度? [英] How do I get the content length of a Django response object?

查看:146
本文介绍了如何获取Django响应对象的内容长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,我尝试记录请求和响应内容的长度,这与Django服务器打印到stderr完全相同。

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

我写了一个简单的中间件如下,但'Content-Length'的值一直为空。

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 

我已经检查了fire-debug,响应标头中有'Content-Length'。但是在中间件中没有Content-Length,print response.items()显示:

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?

推荐答案

如何 len(response.content)?这将给你响应内容中的字符数。我想这不一定与字节数相同。

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.

这篇关于如何获取Django响应对象的内容长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆