Skip to content

Instantly share code, notes, and snippets.

@knzm
Created April 19, 2012 07:20
Show Gist options
  • Select an option

  • Save knzm/2419355 to your computer and use it in GitHub Desktop.

Select an option

Save knzm/2419355 to your computer and use it in GitHub Desktop.
def fix_basic_auth_handler():
# Workaround for http://bugs.python.org/issue9639
if sys.version_info[:2] == (2, 6) and sys.version_info[2] >= 6:
def fixed_http_error_401(self, req, fp, code, msg, headers):
url = req.get_full_url()
response = self.http_error_auth_reqed(
'www-authenticate', url, req, headers)
self.retried = 0
return response
urllib2.HTTPBasicAuthHandler.http_error_401 = fixed_http_error_401
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
from getpass import getpass, _raw_input as raw_input
import urllib2
from urlparse import urlparse, urlunparse
import cookielib
import zlib
import pickle
class UIPasswordMgr(urllib2.HTTPPasswordMgr):
def find_user_password(self, realm, authuri):
parts = urlparse(authuri)
scheme, netloc = parts[:2]
authinfo = urllib2.HTTPPasswordMgr.find_user_password(
self, realm, netloc)
if authinfo != (None, None):
return authinfo
print("HTTP Authorization Required", file=sys.stderr)
print(authuri, file=sys.stderr)
print("realm: %s" % realm, file=sys.stderr)
user = raw_input("User: ", stream=sys.stderr)
passwd = getpass("Password: ", stream=sys.stderr)
self.add_password(realm, netloc, user, passwd)
return (user, passwd)
class Application(object):
def __init__(self, cookie_file=None, password_file=None):
self.jar = cookielib.CookieJar()
self.authman = UIPasswordMgr()
if cookie_file:
self._load_cookie(cookie_file)
if password_file:
self._load_password(password_file)
self.cookie_file = cookie_file
self.password_file = password_file
self._init_opener()
def _init_opener(self):
handlers = [
urllib2.HTTPCookieProcessor(self.jar),
urllib2.HTTPBasicAuthHandler(self.authman),
urllib2.HTTPDigestAuthHandler(self.authman),
]
self.opener = urllib2.build_opener(*handlers)
def save(self):
if self.cookie_file:
self.jar.save()
if self.password_file:
self._save_password(self.password_file)
def _load_cookie(self, cookie_file):
jar = cookielib.MozillaCookieJar(cookie_file)
try:
jar.load()
except IOError:
pass
self.jar = jar
def _load_password(self, filename):
with open(filename, "rb") as f:
data = f.read()
if data:
self.authman.passwd = pickle.loads(zlib.decompress(data))
else:
self.authman.passwd = {}
def _save_password(self, filename):
data = zlib.compress(pickle.dumps(self.authman.passwd))
with open(filename, "wb") as f:
f.write(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment