HTTP Authentication

Gerhard Häring gh at
Mon Apr 6 13:41:10 CEST 2009

Lakshman wrote:
> Whats is the python urllib2 equivallent of
> curl -u username:password status="abcd"
> 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:

# 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 = ""
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

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

-- Gerhard

More information about the Python-list mailing list