More Pythonic?
Jeremy Hylton
jeremy at cnri.reston.va.us
Tue Sep 14 13:35:05 EDT 1999
The way I dealt with this problem in my urllib replacement (see
http://the-tech.mit.edu/~jeremy/python/urllib2.py) was to raise an
exception where the exception instance is actually a valid HTTP
response object.
A typical usage would be something like this:
try:
resp = urllib2.urlopen('http://frob.nitz/')
except HTTPError:
print resp.code, resp.msg
The following excerpt shows just the exception class, which extends
the addinfourl object from the original urllib module.
class HTTPError(URLError, addinfourl):
"""Raised when HTTP error occurs, but also acts like non-error return"""
def __init__(self, url, code, msg, hdrs, fp):
addinfourl.__init__(self, fp, hdrs, url)
self.code = code
self.msg = msg
self.hdrs = hdrs
self.fp = fp
# XXX
self.filename = url
def __str__(self):
return 'HTTP Error %s: %s' % (self.code, self.msg)
def __del__(self):
# XXX is this safe? what if user catches exception, then
# extracts fp and discards exception?
self.fp.close()
Incidentally, have you taken a look at the urllib2 code before? If it
isn't sufficient for your needs, I would be interested to get some
comments or criticism.
Jeremy
More information about the Python-list
mailing list