Skip to content

Instantly share code, notes, and snippets.

@beeftornado
Created June 4, 2014 00:09
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 beeftornado/5c4b441e2e8c82f8d4b6 to your computer and use it in GitHub Desktop.
Save beeftornado/5c4b441e2e8c82f8d4b6 to your computer and use it in GitHub Desktop.
Retrieving basic auth credentials from urllib2's HTTPPasswordMgr for the purpose or transparently transitioning over to requests module.
"""
Assuming you have this lovely gem somewhere else in your app from the old days
..sourcecode:: python
import urllib2
mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
for name, creds in services.items(): # dict of tuples: {name: (uri, user, pass)}
mgr.add_password(None, *creds)
auth = urllib2.HTTPBasicAuthHandler(mgr)
opener = urllib2.build_opener(auth)
urllib2.install_opener(opener) # install it globally for easier access
And then the original dev throws this in right after:
..sourcecode:: python
if 'services' in locals():
del locals()['services'] # don't let normal code see the passwords
And now you want to use `requests`, but can't easily make the basic auth work
without risking security exposure for stuff you don't know about. So
understandably, you don't want to touch this stuff.
"""
import urllib2
import requests
class APIClient(object):
# Root URL to be used for requests
_base_url = None
# The object all requests will go through provided by `requests`.
# It will allow us to stay authenticated after the first request
session = None
def __init__(self):
self.session = requests.Session()
self.session.auth = self._creds
@property
def _creds(self):
# Retrieve basic auth credentials from the depths of python
basic_auth_handlers = [h for h in urllib2._opener.handlers
if isinstance(h,
urllib2.HTTPBasicAuthHandler)]
available_credentials = map(lambda x: \
x.passwd.find_user_password(None,
cfg.site_url),
basic_auth_handlers)
# Return the first available one (if we have no credentials, it will return (None, None), so we're okay
return available_credentials[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment