Authentication from urllib2

Fuzzyman fuzzyman at gmail.com
Fri Oct 22 19:00:04 EDT 2004


I'm trying to do Basic authentication using urllib2 and
HTTPPasswordMgr Objects.

According to my understanding I ought to perform the following simple
sequence (except it doesn't work). Can someone cast their eyes over it
and see what I'm doing wrong please.............

import urllib2 

theurl = 'http://www.somerestrictedserver.com'
username = 'somebody'
password = 'XXXXX'         # a great password
therealm = 'theRealm'

passman = urllib2.HTTPPasswordMgr()     
passman.add_password(therealm, theurl, username, password)     

authhandler = urllib2.HTTPBasicAuthHandler(passman)                 
opener = urllib2.build_opener(authhandler)

req = urllib2.Request(theurl)
filehandle = opener.open(req)
print filehandle.read()

Ideally I would like to use HTTPPasswordMgrWithDefaultRealm() and
specify None for the realm. I would also like to install the opener
and just use urllib2.urlopen rather than using the opener directly. 

When I run this I still get a 401 HTTPError. I would expect the opener
to recognise the realm and retry the request (handle the error using
hte handler I have provided..).

Regards,


Fuzzy
http://www.voidspace.org.uk/atlantibots/pythonutils.html




More information about the Python-list mailing list