Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP Authentication in Python

Whats is the python urllib 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?

like image 562
lprsd Avatar asked Apr 06 '09 10:04

lprsd


1 Answers

The trick is to create a password manager, and then tell urllib about it. Usually, you won't care about the realm of the authentication, just the host/url part. For example, the following:

password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "http://example.com/"
password_mgr.add_password(None, top_level_url, 'user', 'password')
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(urllib2.HTTPHandler, handler)
request = urllib2.Request(url)

Will set the user name and password to every URL starting with top_level_url. Other options are to specify a host name or more complete URL here.

A good document describing this and more is at http://www.voidspace.org.uk/python/articles/urllib2.shtml#id6.

like image 98
Ivo Avatar answered Sep 28 '22 09:09

Ivo