Basic Authentication in Python urllib2

Yesterday I’m playing around with github api with urllib and found a problem to perform basic authentication when I sent request to API. I’m not using requests because too lazy to install third party dependency. 😀

Here is it..

import urllib2
import base64

request = urllib2.Request("")
credential = base64.encodestring('{user}:{pwd}'.format(user=username, pwd=password)).replace('\n', '')
request.add_header('Authorization', 'Basic {credential}'.format(credential=credential))   
result = urllib2.urlopen(request)



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s