2012-08-12 53 views
0

我试图在发生错误时记录一些连接信息。使用httplib的的HttpConnection的,我可以通过调试级别设置为1,打印出的请求头:Python HttpConnection - 将请求标头写入文件

connection = httplib.HTTPConnection('www.example.com') 
    connection.set_debuglevel(1) 

不过,这似乎只是直接打印到外壳无条件。我需要能够获得这个信息作为一个字符串或东西存储在一个变量,这样我只有在抛出异常时才打印出来。

我想要的具体信息是库生成的请求标头。

+1

也许你应该使用更高级别的模块呢? stdlib中的'urllib2'或'requests'或类似的库作为附加组件。 – 2012-08-12 12:10:36

回答

0

原来,诀窍是将sys.stdout重定向到一个StringIO对象,然后可以将它的内容写入文件,或者您可以将它写入字符串。查看StringIO.StringIO。

1

我会使用requests HTTP库。

要得到响应头,你只需要这小小的一段代码:

import requests 

try: 
    r = requests.get("http://www.example.com") 
    # Raise an exception in case of "bad" 
    # status code (non-200 response) 
    r.raise_for_status() 
    print r.headers 
except Exception as e: 
    print e.message 

输出:

{'connection': 'close', 
'content-encoding': 'gzip', 
'content-length': '1162', 
'content-type': 'text/html; charset=UTF-8', 
'date': 'Sun, 12 Aug 2012 12:49:44 GMT', 
'last-modified': 'Wed, 09 Feb 2011 17:13:15 GMT', 
'server': 'Apache/2.2.3 (CentOS)', 
'vary': 'Accept-Encoding'}