Create a gist now

Instantly share code, notes, and snippets.

Basic request - Python
def basic_request(request, verbose=False):
""" request is in form of a urllib2.Request()
Return (False, error) OR
(True, response, url, info)
"""
error = False
result = []
try:
response = urlopen(request,timeout=100)
except IOError, e:
if hasattr(e,'reason'):
error = ("FAILED to reach server", e.reason)
elif hasattr(e, 'code'):
error = ("FAIL - Server could not fulfill request", e.code)
except Exception as inst:
error = ("unspecified error occurred", inst.args)
else: # all good
result = (response.read(), response.geturl(), response.info())
if verbose:
print "Requested:\n %s" % request
print "Response:\n %s" % result
return (True, result)
# Failed - return error codes
if verbose:
print "Error", error
return (False, error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment