HTTP Authentication using urllib2

Lakshman scorpion032 at gmail.com
Fri Apr 24 07:25:20 EDT 2009


I am trying to authenticate using urllib2. The basic authentication
works if I hard code authheaders.
def is_follows(follower, following):

    theurl = 'http://twitter.com/friendships/exists.json?
user_a='+follower+'&user_b='+following
    username = 'uname1'
    password = 'pwd1'

    handle = urllib2.Request(theurl)

    authheader =  "Basic %s" % base64.encodestring('%s:%s' %
(username, password))
    handle.add_header("Authorization", authheader)

    try:
        return simplejson.load(urllib2.urlopen(handle))
    except IOError, e:
        print "Something wrong. This shouldnt happen"


I am trying to refactor this code into how urllib2 expects to do. But
I am getting an error.

def is_follows(follower, following):

    url = 'http://twitter.com/friendships/exists.json?user_a=%s&user_b=
%s' %(
        follower, following)


    #Authenticate once for all
    auth_handler = urllib2.HTTPBasicAuthHandler()
    auth_handler.add_password(realm='',
                              uri='http://twitter.com',
                              user='scorpion032',
                              passwd='123456')
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)

    try:
        return simplejson.load(urllib2.urlopen(url))
    except:
        print "Something wrong. This shouldnt happen"
        return False

Can U please point what I am missing. As I understand, the Auth
Headers are put appropriately in either cases, but the latter one
doesnt work.



More information about the Python-list mailing list