[Tutor] urllib2 issue getting realm

Johan Geldenhuys johan at accesstel.com.au
Wed Aug 31 09:46:19 CEST 2011


Hi everybody,

I am trying to use a very simple piece of code to get the realm from
different HTTPS URLs.

This realm is essential for successful authentication on the HTTPS session.

If have to run this for a few different hosts and capture the realm.
For one host, it works perfectly, but when I try the same code to get the
next realm, it fails. I suspect that I need to close some type of
connections or something, but I can't put my finger on it.

This what I try:

>>> ips = ['192.168.10.190', '192.168.10.191', '192.168.10.192',
'192.168.10.193']
>>> URL = "https://%s/axis-cgi/jpg/image.cgi?resolution=1280x800"
>>> import urllib2
>>> try:
...     req = urllib2.Request(URL % ips[0])
...     handle = urllib2.urlopen(req)
... except IOError, e:
...     print `e`
...     
HTTPError()
>>> 
>>> e
HTTPError()
>>> authline = e.headers.get('www-authenticate', '')
>>> authline
'Digest realm="AXIS_00408CB71F14",
nonce="0002c497Y6450989253d0ea85587e89821031c60ab9768", stale=FALSE,
qop="auth", Basic realm="AXIS_00408CB71F14"'
>>>
>>> handle
  File "<console>", line 1, in <module>
''' <type 'exceptions.NameError'> : name 'handle' is not defined '''
>>> req
<urllib2.Request instance at 0x07A67990>
>>> req.host
'192.168.10.190'
>>>



At this point, I am happy. It worked. I expect the try to fail to get the
exception.

For the next one:

>>> try:
...     req = urllib2.Request(URL % ips[1])
...     handle = urllib2.urlopen(req)
... except IOError, e:
...     print `e`
...     
>>>

See, no "e" printed which means that something worked. The exception didn't
happen and I don't know why...Anybody?

I tried doing this:

>>> del req
>>> del handle
>>> del e

But with the same result:

>>> try:
...     req = urllib2.Request(URL % ips[1])
...     handle = urllib2.urlopen(req)
... except IOError, e:
...     print `e`
...     
>>> e
  File "<console>", line 1, in <module>
''' <type 'exceptions.NameError'> : name 'e' is not defined '''
>>> req
<urllib2.Request instance at 0x07B7BDF0>
>>> handle
<addinfourl at 129502424 whose fp = <socket._fileobject object at
0x07B7C670>>




Regards 
  
Johan 





More information about the Tutor mailing list