tags:

views:

102

answers:

1

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?

+3  A: 

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:

try:
    urllib2.urlopen(req)
except urllib2.HTTPError, e:
    print "Response code",e.code # prints 404
    print "Response body",e.read() # prints the body of the response...
                                   # ie: your XML
    print "Headers",e.headers.headers

Original

In this case, given that you're using HTTP as your transport protocol, you'll probably have more luck with the httplib library:

>>> import httplib
>>> conn = httplib.HTTPConnection("www.stackoverflow.com")
>>> conn.request("GET", "/dlkfjadslkfjdslkfjd.html")
>>> r = conn.getresponse()
>>> r.status
301
>>> r.reason
'Moved Permanently'
>>> r.read()
'<head><title>Document Moved</title></head>\n<body><h1>Object Moved</h1>
 This document may be found   
 <a HREF="http://stackoverflow.com/dlkfjadslkfjdslkfjd.html"&gt;here&lt;/a&gt;&lt;/body&gt;'

You can further use r.getheaders() and so forth to inspect other aspects of the response.

Jarret Hardie
Correct me if I'm wrong, but I can't use the urllib2.Request class with HTTPConnection.
John Giotta
You are indeed correct. Is there something particular in the Request class that you're using?
Jarret Hardie
Yes, byte string, or more accurately, a zip file.
John Giotta