HTTP Authentication using urllib2

L

Lakshman

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.
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top