I’m working with an API which I post files to. However, when I receive the response, the HTTP status code is a 202. This is to be expected, but in addition the API will also respond with XML content.
So in my try/except block urllib2.urlopen will result in a raised urllib2.HTTPError and destroying the XML content.
try:
response = urllib2.urlopen(req)
except urllib2.HTTPError, http_e:
if http_e.code == 202:
print 'accepted!'
pass
print response.read() # UnboundLocalError: local variable 'response' referenced before assignment
How can I expect the 202 and keep the response content, but not raise an error?
Edit
Being silly, I forgot to inspect the exception that is returned by urllib2. It features all of the properties I’ve been waxing on about for httplib. This should do the trick for you:
Original
In this case, given that you’re using HTTP as your transport protocol, you’ll probably have more luck with the httplib library:
You can further use
r.getheaders()and so forth to inspect other aspects of the response.