473,395 Members | 2,468 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Error Codes From a URLError

I've written a CGI proxy that remotely fetches web pages. I use the
urlopen function in CLientCookie which replaces (and ultimately uses)
the urlopen function in urllib2. What I'd like to do is give a more
useful message to the user when the page fetch fails.

My understanding was that a URLError exception had a 'code' attribute
which was the error code.

I trap the error with a simple : (excuse the horrible indentation,
this is from the middle of a program)

try:
req = urllib2.Request(theurl, txdata, txheaders)
if data['name'] and data['pass']:
import base64
base64string = base64.encodestring('%s:%s' %
(data['name'], data['pass']))[:-1]
req.add_header("Authorization", "Basic %s" %
base64string)
u = openfun(req)
......
except IOError, e: # an error in fetching
the page will raise a URLError which is a subclass of IOError
if not cdone:
print "Content-type: text/html" # this is the
header to the server
print # so is this
blank line
if not hasattr(e, 'code'): # If it's not
an http error - raise it as an error
raise

elif e.code == 401: #
authorisation
print authmess % (theurl, data['mod'])
print authend

elif e.code in errorlist: # standard
http errors
the_err = errorlist[e.code]
print err_mes % (the_err[0], the_err[0], the_err[1])

else: # any others
raise

openfun is urlopen function from ClientCookie (if available) or from
urllib2.

What ought to happen in my limied understanding, is that the exception
(e) should have the attribute 'code' if it a URLError - and that value
ought to tell me what type of error it is... (the error message is
then ina dictionary called errorlist which I nicked from
BaseHTTPServer).

*However*, when I use it to try to fetch a non-existent page
(expecting a 404 error) - it falls at the first raise statement.
Evidently the exception *is* an IOError, but doesn't have the code
attribute.
*However* - you see the explicit test for a 401 (authentication)
error. I have code that can handle authentication... if I go to a page
that requires authentication it picks it up fine...... (so the
URLError in that case does have the code attribute).

The exact error traceback is below - and you can see where urllib2
raises the URLError - because of what it sees as a socket problem...
but it obviously isn't returning the error code properly. Any
suggestions ?

URLError Python 2.2.2: /usr/bin/python
Fri Jul 23 11:06:39 2004

A problem occurred in a Python script. Here is the sequence of
function calls leading up to the error, in the order they occurred.

/home/buildin/public_html/cgi-bin/approx.py
280 print "Content-type: text/html" # this
is the header to the server

281 print # so is
this blank line

282 if not hasattr(e, 'code'): # If
it's not an http error - raise it as an error

283 raise

284

hasattr undefined, e = <urllib2.URLError instance>
/home/buildin/public_html/cgi-bin/ClientCookie/_urllib2_support.py in
urlopen(url=<urllib2.Request instance>, data=None)
969 finally:

970 urlopen_lock.release()

971 return _opener.open(url, data)

972

973 def urlretrieve(url, filename=None, reporthook=None,
data=None):

global _opener = <ClientCookie._urllib2_support.OpenerDirector
instance>, _opener.open = <bound method OpenerDirector.open of
<ClientCookie._urllib2_support.OpenerDirector instance>>, url =
<urllib2.Request instance>, data = None
/home/buildin/public_html/cgi-bin/ClientCookie/_urllib2_support.py in
open(self=<ClientCookie._urllib2_support.OpenerDir ector instance>,
fullurl=<urllib2.Request instance>, data=None)
567 req = meth(req)

568

569 response = urllib2.OpenerDirector.open(self, req,
data)

570

571 # post-process response

response undefined, global urllib2 = <module 'urllib2' from
'/usr/lib/python2.2/urllib2.pyc'>, urllib2.OpenerDirector = <class
urllib2.OpenerDirector>, urllib2.OpenerDirector.open = <unbound method
OpenerDirector.open>, self =
<ClientCookie._urllib2_support.OpenerDirector instance>, req =
<ClientCookie._urllib2_support.Request instance>, data = None
/usr/lib/python2.2/urllib2.py in
open(self=<ClientCookie._urllib2_support.OpenerDir ector instance>,
fullurl=<ClientCookie._urllib2_support.Request instance>, data=None)
320 type_ = req.get_type()

321 result = self._call_chain(self.handle_open, type_, type_
+ \

322 '_open', req)

323 if result:

324 return result

req = <ClientCookie._urllib2_support.Request instance>
/usr/lib/python2.2/urllib2.py in
_call_chain(self=<ClientCookie._urllib2_support.Op enerDirector
instance>, chain={'file': [<urllib2.FileHandler instance>], 'ftp':
[<urllib2.FTPHandler instance>], 'http':
[<ClientCookie._urllib2_support.HTTPHandler instance>], 'https':
[<ClientCookie._urllib2_support.HTTPSHandler instance>], 'unknown':
[<urllib2.UnknownHandler instance>]}, kind='http',
meth_name='http_open', *args=(<ClientCookie._urllib2_support.Request
instance>,))
299 func = getattr(handler, meth_name)

300

301 result = func(*args)

302 if result is not None:

303 return result

result undefined, func = <bound method HTTPHandler.http_open of
<ClientCookie._urllib2_support.HTTPHandler instance>>, args =
(<ClientCookie._urllib2_support.Request instance>,)
/home/buildin/public_html/cgi-bin/ClientCookie/_urllib2_support.py in
http_open(self=<ClientCookie._urllib2_support.HTTP Handler instance>,
req=<ClientCookie._urllib2_support.Request instance>)
883 class HTTPHandler(AbstractHTTPHandler):

884 def http_open(self, req):

885 return self.do_open(httplib.HTTP, req)

886

887 http_request = AbstractHTTPHandler.do_request_

self = <ClientCookie._urllib2_support.HTTPHandler instance>,
self.do_open = <bound method HTTPHandler.do_open of
<ClientCookie._urllib2_support.HTTPHandler instance>>, global httplib
= <module 'httplib' from '/usr/lib/python2.2/httplib.pyc'>,
httplib.HTTP = <class httplib.HTTP>, req =
<ClientCookie._urllib2_support.Request instance>
/home/buildin/public_html/cgi-bin/ClientCookie/_urllib2_support.py in
do_open(self=<ClientCookie._urllib2_support.HTTPHa ndler instance>,
http_class=<class httplib.HTTP>,
req=<ClientCookie._urllib2_support.Request instance>)
728 h.endheaders()

729 except socket.error, err:

730 raise URLError(err)

731 if req.has_data():

732 h.send(req.get_data())

global URLError = <class urllib2.URLError>, err = <socket.gaierror
instance>
URLError:
__doc__ = None
__getitem__ = <bound method URLError.__getitem__ of
<urllib2.URLError instance>>
__init__ = <bound method URLError.__init__ of <urllib2.URLError
instance>>
__module__ = 'urllib2'
__str__ = <bound method URLError.__str__ of <urllib2.URLError
instance>>
reason = <socket.gaierror instance>

Regards,
Fuzzy

http://www.voidspace.org.uk/atlantib...thonutils.html
Jul 18 '05 #1
2 4718
On 23 Jul 2004, Fuzzyman wrote:
*However*, when I use it to try to fetch a non-existent page
(expecting a 404 error) - it falls at the first raise statement.
Evidently the exception *is* an IOError, but doesn't have the code
attribute.


For the "non-existent page", are you using a url of the form
'http://fake.server/some/file' or 'http://real.server/fake/file'?
Because if the host is nonexistent (and therefore a connection can't be
opened), then I'd expect urllib2 to raise an IOError. I'd expect an
HTTPError only if the server exists and explicitly returns a 404.

Jul 18 '05 #2
Christopher T King <sq******@WPI.EDU> wrote in message news:<Pi**************************************@ccc 8.wpi.edu>...
On 23 Jul 2004, Fuzzyman wrote:
*However*, when I use it to try to fetch a non-existent page
(expecting a 404 error) - it falls at the first raise statement.
Evidently the exception *is* an IOError, but doesn't have the code
attribute.


For the "non-existent page", are you using a url of the form
'http://fake.server/some/file' or 'http://real.server/fake/file'?
Because if the host is nonexistent (and therefore a connection can't be
opened), then I'd expect urllib2 to raise an IOError. I'd expect an
HTTPError only if the server exists and explicitly returns a 404.


Right - that would explain it.
But it makes it difficult to trap the errors - an IOError *might* mean
the page is non-existent... *or* it might mean another problem !!

Oh well.

Thanks

Fuzzy

http://www.voidspace.org.uk/atlantib...thonutils.html
Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Matt | last post by:
I'm trying to get the HTML data off of a webpage. Let's say for the sake of argument it's the python homepage. I've googled around and found some examples that people said worked. Here's what...
0
by: Benjamin Schollnick | last post by:
Folks, With Windows XP, and Python v2.41 I am running into a problem.... The following code gives me an unknown protocol error.... And I am not sure how to resolve it... I have a API...
1
by: joemynz | last post by:
Help please with a URLError. Invoking a url that works in Firefox and IE results in a "urlerror 7, no address ..." in python. I need to debug why. Traceback is below. There's a redirect when the...
0
by: mh121 | last post by:
Hi, I am trying to input a spreadsheet of possible domain names and output the length of the sourcecode of the webpage (if it exists). In testing this, I’ve come across a lot of errors, for...
0
by: Jinshi | last post by:
Hello, everyone, I am quite new to python and I don't know how to solve this problem. I hope someone can help me. I just did a test in python shell: Traceback (most recent call last): File...
0
by: Penny Y. | last post by:
Hello, I run this small script: import urllib2,sys try: r=urllib2.urlopen("http://un-know-n.com/") except URLError,e: print str(e) sys.exit(1)
1
by: Gabriel Genellina | last post by:
En Tue, 15 Apr 2008 02:54:43 -0300, Penny Y. <pylists@arcor.deescribió: Same as the function urlopen, you have to qualify URLError with the module first: except urllib2.URLError, e: ... ...
2
hyperpau
by: hyperpau | last post by:
Before anything else, I am not a very technical expert when it comes to VBA coding. I learned most of what I know by the excellent Access/VBA forum from bytes.com (formerly thescripts.com). Ergo, I...
4
by: Mike Driscoll | last post by:
Hi, I have been using the following code for over a year in one of my programs: f = urllib2.urlopen('https://www.companywebsite.com/somestring') It worked great until the middle of the...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.