我正在使用Harvest API(http://www.getharvest.com/api)。当客户端超过其配额时,将返回503响应。在该响应中,应该有一个名为“Retry-After”的标题告诉我在再次尝试之前需要等待多长时间。
如果呼叫失败,如何访问响应标头?我抓住HTTPError异常,但无法弄清楚如何从中获取标题。
我可以使用exception.read()获取响应主体,但这只是没有标题的主体。
一些相关代码:
try:
request = urllib2.Request( url=self.uri+url, headers=self.headers )
r = urllib2.urlopen(request)
xml = r.read()
return parseString( xml )
except urllib2.HTTPError as err:
logger.debug("EXCEPTION: %s" % err.read() )
答案 0 :(得分:5)
试试这个:
logger.debug(err.headers)
这是一本字典,因此使用err.headers['Retry-After']
答案 1 :(得分:1)
(Pdb) pp err.__dict__
{'__iter__': <bound method _fileobject.__iter__ of <socket._fileobject object at 0x2b9a8e923950>>,
'code': 404,
'fileno': <bound method _fileobject.fileno of <socket._fileobject object at 0x2b9a8e923950>>,
'fp': <addinfourl at 47942867504160 whose fp = <socket._fileobject object at 0x2b9a8e923950>>,
'hdrs': <httplib.HTTPMessage instance at 0x2b9a91964a70>,
'headers': <httplib.HTTPMessage instance at 0x2b9a91964a70>,
'msg': 'Not Found',
'next': <bound method _fileobject.next of <socket._fileobject object at 0x2b9a8e923950>>,
'read': <bound method _fileobject.read of <socket._fileobject object at 0x2b9a8e923950>>,
'readline': <bound method _fileobject.readline of <socket._fileobject object at 0x2b9a8e923950>>,
'readlines': <bound method _fileobject.readlines of <socket._fileobject object at 0x2b9a8e923950>>,
'url': 'http://www.heise.de/fo'}
所有相关的响应信息都可以从捕获的异常中获得。
答案 2 :(得分:0)
err.read()返回body,err.info()返回标题