2011-05-15 50 views
1

我使用Harvest API(http://www.getharvest.com/api)。當客戶結束它的配額時,返回503響應。在那個響應中,應該有一個名爲「Retry-After」的標題,告訴我在再次嘗試之前需要等待多久。如何使用urlib2訪問錯誤上的響應頭?

如何在通話失敗時訪問響應頭?我抓住了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()) 

回答

3

試試這個:

logger.debug(err.headers) 

這是一本字典,從而使用err.headers['Retry-After']

+0

謝謝,這是有效的。不幸的是,他們實際上並沒有發送文檔標題,他們會發送:( – 2011-05-15 17:35:13

+0

你檢查wireshark/firebug的確切響應?也許python的解析是錯誤的或什麼? – 2011-05-15 17:36:48

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'} 

所有相關的響應信息都可以從捕獲的異常。

0

err.read()返回正文,而err.info()返回標題