HTTP Authentication

L

Lakshman

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?
 
G

Gerhard Häring

Lakshman said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top