Skip to content

Instantly share code, notes, and snippets.

@rollys
Forked from kennethreitz/0_urllib2.py
Created February 11, 2014 16:50
Show Gist options
  • Save rollys/8938879 to your computer and use it in GitHub Desktop.
Save rollys/8938879 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
gh_url = 'https://api.github.com'
req = urllib2.Request(gh_url)
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, gh_url, 'user', 'pass')
auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)
urllib2.install_opener(opener)
handler = urllib2.urlopen(req)
print handler.getcode()
print handler.headers.getheader('content-type')
# ------
# 200
# 'application/json'
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
r = requests.get('https://api.github.com', auth=('user', 'pass'))
print r.status_code
print r.headers['content-type']
# ------
# 200
# 'application/json'
@rollys
Copy link
Author

rollys commented Feb 11, 2014

I think that the urllib2 example is a straw man. Here is a code, that I use in my code to access github using urllib2:

import urllib2
from base64 import encodestring

request = urllib2.Request('https://api.github.com/user')
base64string = encodestring('%s:%s' % ('user', 'pass')).replace('\n', '')
request.add_header('Authorization', 'Basic %s' % base64string)
r = urllib2.urlopen(request)

print r.getcode()
print r.headers["content-type"]
print r.headers["X-RateLimit-Limit"]

Here is the same code using requests:

import requests

r = requests.get('https://api.github.com/user', auth=('user', 'pass'))

print r.status_code
print r.headers['content-type']
print r.headers['X-RateLimit-Limit']

Both print (make sure you change your username and password):

200
application/json
5000
While the requests code is much simpler, the urllib2 code is much better than your original example: you just need to specify the url once (not twice), as well as you access the headers in the same way as in requests. And it's 4 lines (to open the url), not 8 lines as in your original example. So one should be fair.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment