HTTP Authentication

Gerhard Häring gh at ghaering.de
Mon Apr 6 07:41:10 EDT 2009


Lakshman wrote:
> Whats is the python urllib2 equivallent of
> 
> curl -u username:password status="abcd" http://example.com/update.json
> 
> I did this:
> 
> handle = urllib2.Request(url)
> authheader =  "Basic %s" % base64.encodestring('%s:%s' % (username,
> password))
> handle.add_header("Authorization", authheader)
> 
> Is there a better / simpler way?

Better? Yes.
Simpler? No.

Actually, the proper way using the urllib2 API is more code.

When I need it some time ago, I googled and used this recipe:

http://www.voidspace.org.uk/python/articles/urllib2.shtml#id6


# create a password manager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
# If we knew the realm, we could use it instead of ``None``.
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)

handler = urllib2.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(handler)

# use the opener to fetch a URL
opener.open(a_url)

# Install the opener.
# Now all calls to urllib2.urlopen use our opener.
urllib2.install_opener(opener)

-- Gerhard




More information about the Python-list mailing list