Skip to content

Instantly share code, notes, and snippets.

@hiorws
Forked from kennethreitz/0_urllib2.py
Created November 9, 2016 01:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiorws/c5fc4764d99b13a64f4d3a70dca6fdb7 to your computer and use it in GitHub Desktop.
Save hiorws/c5fc4764d99b13a64f4d3a70dca6fdb7 to your computer and use it in GitHub Desktop.
urllib2 vs requests
#!/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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment