How do I access response headers on an error using urlib2?
I'm using the Harvest API (http://www.getharvest.com/api). When a client goes over it's quota, a 503 response is returned. In that response there should be a header called "Retry-After" that tells me how long to wait before trying again.
How do I access the response headers when the call fails? I'm grabbing the HTTPError exception, but can't figure out how to get the headers out of it.
I can get the response body with exception.read(), but that's just the body without headers.
Some relevant code:
开发者_Python百科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() )
Try this:
logger.debug(err.headers)
It's a dictionary, thus use err.headers['Retry-After']
(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'}
All related response information are available from the caught exception.
err.read() returns body, and err.info() returns headers
精彩评论