Add in a proper AuthManager instead of the list version that was being used.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Added support for all Auth types that python supports
authored by digitalxero · committed by digitalxero · parent a9e18e9 · Browse files · 4 files·+158 added−102 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+158 added−102 removed
- other:+158 added−102 removed
Provenance
- Commit
edfdef2- Tree
a414691- Author
digitalxero <none@none>- Committer
digitalxero <none@none>- Parent
a9e18e9
4 files changed+158 added−102 removed
modified:requests/async.py+1 added-1 removed
31 unmodified lines32 raise ImportError('No Async adaptations of urllib2 found!')33 34 from .core import *35 36-__all__ = ['Request', 'Response', 'request', 'get', 'head', 'post', 'put', 'delete', 'add_autoauth', 'AUTOAUTHS',36+__all__ = ['Request', 'Response', 'request', 'get', 'head', 'post', 'put', 'delete', 'auth_manager', 'AuthObject',37 'RequestException', 'AuthenticationError', 'URLRequired', 'InvalidMethod', 'HTTPError']38 __title__ = 'requests'39 __version__ = '0.0.1'40 __build__ = 0x0000013 unmodified linesmodified:requests/core.py+155 added-70 removed
16 unmodified lines17 18 from .packages.poster.encode import multipart_encode19 from .packages.poster.streaminghttp import register_openers20 21-__all__ = ['Request', 'Response', 'request', 'get', 'head', 'post', 'put', 'delete', 'add_autoauth', 'AUTOAUTHS',21+__all__ = ['Request', 'Response', 'request', 'get', 'head', 'post', 'put', 'delete', 'auth_manager', 'AuthObject',22 'RequestException', 'AuthenticationError', 'URLRequired', 'InvalidMethod', 'HTTPError']23 __title__ = 'requests'24 __version__ = '0.2.5'25 __build__ = 0x00020526-__author__ = 'Kenneth Reitz'26+__author__ = 'Kenneth Reitz, Dj Gilcrease'27 __license__ = 'ISC'28 __copyright__ = 'Copyright 2011 Kenneth Reitz'29 30-31-AUTOAUTHS = []32-30 class _Request(urllib2.Request):31 """Hidden wrapper around the urllib2.Request object. Allows for manual32 setting of HTTP methods.33 """31 unmodified lines65 self.data = data66 67 self.response = Response()68 69+ if isinstance(auth, (list, tuple)):70+ auth = AuthObject(*auth)71+ if not auth:72+ auth = auth_manager.get_auth(self.url)73 self.auth = auth74 self.cookiejar = cookiejar75 self.sent = False76 17 unmodified lines94 """Creates appropriate opener object for urllib2."""95 96 _handlers = []97 97- if self.auth or self.cookiejar:98- if self.auth:99- authr = urllib2.HTTPPasswordMgrWithDefaultRealm()98+ if self.auth:99+ if not isinstance(self.auth.handler, (urllib2.AbstractBasicAuthHandler, urllib2.AbstractDigestAuthHandler)):100+ auth_manager.add_password(self.auth.realm, self.url, self.auth.username, self.auth.password)101+ self.auth.handler = self.auth.handler(auth_manager)102+ auth_manager.add_auth(self.url, self.auth)103 101- authr.add_password(None, self.url, self.auth[0], self.auth[1])102- auth_handler = urllib2.HTTPBasicAuthHandler(authr)104+ _handlers.append(self.auth.handler)105 104- _handlers.append(auth_handler)105-106- if self.cookiejar:107- cookie_handler = urllib2.HTTPCookieProcessor(cookiejar)108- _handlers.append(cookie_handler)109-106+ if self.cookiejar:107+ cookie_handler = urllib2.HTTPCookieProcessor(cookiejar)108+ _handlers.append(cookie_handler)109+ if _handlers:110 opener = urllib2.build_opener(*_handlers)111 return opener.open112-112 else:113 return urllib2.urlopen114 115 116 def _build_response(self, resp):117 """Build internal Response object from given response."""118 119 self.response.status_code = resp.code121- self.response.headers = resp.info().dict120+ self.response.headers = resp.info().dict or resp.headers121 self.response.content = resp.read()122 self.response.url = resp.url123 124 35 unmodified lines160 self.response.error = why161 else:162 self._build_response(resp)163 self.response.ok = True164+165- self.response.cached = False165+ self.response.cached = False166 else:167 self.response.cached = True168 169 28 unmodified lines198 """Raises stored HTTPError if one exists."""199 if self.error:200 raise self.error201 202+class AuthManager(object):203+ def __new__(cls):204+ singleton = cls.__dict__.get('__singleton__')205+ if singleton is not None:206+ return singleton207 208+ cls.__singleton__ = singleton = object.__new__(cls)209+210+ return singleton211+212+ def __init__(self):213+ self.passwd = {}214+ self._auth = {}215+216+ def add_auth(self, uri, auth):217+ uri = self.reduce_uri(uri, False)218+ self._auth[uri] = auth219+220+ def add_password(self, realm, uri, user, passwd):221+ # uri could be a single URI or a sequence222+ if isinstance(uri, basestring):223+ uri = [uri]224+ reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])225+ if reduced_uri not in self.passwd:226+ self.passwd[reduced_uri] = {}227+ self.passwd[reduced_uri] = (user, passwd)228+229+ def find_user_password(self, realm, authuri):230+ for uris, authinfo in self.passwd.iteritems():231+ reduced_authuri = self.reduce_uri(authuri, False)232+ for uri in uris:233+ if self.is_suburi(uri, reduced_authuri):234+ return authinfo235+236+ return (None, None)237+238+ def get_auth(self, uri):239+ uri = self.reduce_uri(uri, False)240+ return self._auth.get(uri, None)241+242+ def reduce_uri(self, uri, default_port=True):243+ """Accept authority or URI and extract only the authority and path."""244+ # note HTTP URLs do not have a userinfo component245+ parts = urllib2.urlparse.urlsplit(uri)246+ if parts[1]:247+ # URI248+ scheme = parts[0]249+ authority = parts[1]250+ path = parts[2] or '/'251+ else:252+ # host or host:port253+ scheme = None254+ authority = uri255+ path = '/'256+ host, port = urllib2.splitport(authority)257+ if default_port and port is None and scheme is not None:258+ dport = {"http": 80,259+ "https": 443,260+ }.get(scheme)261+ if dport is not None:262+ authority = "%s:%d" % (host, dport)263+ return authority, path264+265+ def is_suburi(self, base, test):266+ """Check if test is below base in a URI tree267+268+ Both args must be URIs in reduced form.269+ """270+ if base == test:271+ return True272+ if base[0] != test[0]:273+ return False274+ common = urllib2.posixpath.commonprefix((base[1], test[1]))275+ if len(common) == len(base[1]):276+ return True277+ return False278+279+ def empty(self):280+ self.passwd = {}281+282+ def remove(self, uri, realm=None):283+ # uri could be a single URI or a sequence284+ if isinstance(uri, basestring):285+ uri = [uri]286+287+ for default_port in True, False:288+ reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])289+ del self.passwd[reduced_uri][realm]290+291+ def __contains__(self, uri):292+ # uri could be a single URI or a sequence293+ if isinstance(uri, basestring):294+ uri = [uri]295+296+ uri = tuple([self.reduce_uri(u, False) for u in uri])297+298+ if uri in self.passwd:299+ return True300+301+ return False302+303+auth_manager = AuthManager()304+305+306+class AuthObject(object):307+ """The :class:`AuthObject` is a simple HTTP Authentication token. When308+ given to a Requests function, it enables Basic HTTP Authentication for that309+ Request. You can also enable Authorization for domain realms with AutoAuth.310+ See AutoAuth for more details.311+312+ :param username: Username to authenticate with.313+ :param password: Password for given username.314+ :param realm: (optional) the realm this auth applies to315+ :param handler: (optional) basic || digest || proxy_basic || proxy_digest316+ """317+318+ _handlers = {319+ 'basic': urllib2.HTTPBasicAuthHandler,320+ 'digest': urllib2.HTTPDigestAuthHandler,321+ 'proxy_basic': urllib2.ProxyBasicAuthHandler,322+ 'proxy_digest': urllib2.ProxyDigestAuthHandler323+ }324+325+ def __init__(self, username, password, handler='basic', realm=None):326+ self.username = username327+ self.password = password328+ self.realm = realm329+330+ self.handler = self._handlers.get(handler.lower(), urllib2.HTTPBasicAuthHandler)331+332+333 def request(method, url, **kwargs):334 """Sends a `method` request. Returns :class:`Response` object.335 336 :param method: method for the new :class:`Request` object.8 unmodified lines345 data = kwargs.pop('data', {}) or kwargs.pop('params', {})346 347 r = Request(method=method, url=url, data=data, headers=kwargs.pop('headers', {}),348 cookiejar=kwargs.pop('cookies', None), files=kwargs.pop('files', None),219- auth=_detect_auth(url, kwargs.pop('auth', None)))349+ auth=kwargs.pop('auth', auth_manager.get_auth(url)))350 r.send()351 352 return r.response353 6 unmodified lines360 :param cookies: (optional) CookieJar object to send with the :class:`Request`.361 :param auth: (optional) AuthObject to enable Basic HTTP Auth.362 """363 234- return request('GET', url, params=params, headers=headers, cookiejar=cookies,235- auth=_detect_auth(url, auth))364+ return request('GET', url, params=params, headers=headers, cookiejar=cookies, auth=auth)365 366 367 def head(url, params={}, headers={}, cookies=None, auth=None):368 """Sends a HEAD request. Returns :class:`Response` object.4 unmodified lines373 :param cookies: (optional) CookieJar object to send with the :class:`Request`.374 :param auth: (optional) AuthObject to enable Basic HTTP Auth.375 """376 248- return request('HEAD', url, params=params, headers=headers, cookiejar=cookies,249- auth=_detect_auth(url, auth))377+ return request('HEAD', url, params=params, headers=headers, cookiejar=cookies, auth=auth)378 379 380 def post(url, data={}, headers={}, files=None, cookies=None, auth=None):381 """Sends a POST request. Returns :class:`Response` object.5 unmodified lines387 :param cookies: (optional) CookieJar object to send with the :class:`Request`.388 :param auth: (optional) AuthObject to enable Basic HTTP Auth.389 """390 263- return request('POST', url, data=data, headers=headers, files=files, cookiejar=cookies,264- auth=_detect_auth(url, auth))391+ return request('POST', url, data=data, headers=headers, files=files, cookiejar=cookies, auth=auth)392 393 394 def put(url, data=b'', headers={}, files={}, cookies=None, auth=None):395 """Sends a PUT request. Returns :class:`Response` object.5 unmodified lines401 :param cookies: (optional) CookieJar object to send with the :class:`Request`.402 :param auth: (optional) AuthObject to enable Basic HTTP Auth.403 """404 278- return request('PUT', url, data=data, headers=headers, files=files, cookiejar=cookies,279- auth=_detect_auth(url, auth))405+ return request('PUT', url, data=data, headers=headers, files=files, cookiejar=cookies, auth=auth)406 407 408 def delete(url, params={}, headers={}, cookies=None, auth=None):409 """Sends a DELETE request. Returns :class:`Response` object.4 unmodified lines414 :param cookies: (optional) CookieJar object to send with the :class:`Request`.415 :param auth: (optional) AuthObject to enable Basic HTTP Auth.416 """417 292- return request('DELETE', url, params=params, headers=headers, cookiejar=cookies,293- auth=_detect_auth(url, auth))418+ return request('DELETE', url, params=params, headers=headers, cookiejar=cookies, auth=auth)419 295-296-def add_autoauth(url, authobject):297- """Registers given AuthObject to given URL domain. for auto-activation.298- Once a URL is registered with an AuthObject, the configured HTTP299- Authentication will be used for all requests with URLS containing the given300- URL string.301-302- Example: ::303- >>> c_auth = requests.AuthObject('kennethreitz', 'xxxxxxx')304- >>> requests.add_autoauth('https://convore.com/api/', c_auth)305- >>> r = requests.get('https://convore.com/api/account/verify.json')306- # Automatically HTTP Authenticated! Wh00t!307-308- :param url: Base URL for given AuthObject to auto-activate for.309- :param authobject: AuthObject to auto-activate.310- """311-312- global AUTOAUTHS313-314- AUTOAUTHS.append((url, authobject))315-316-317-def _detect_auth(url, auth):318- """Returns registered AuthObject for given url if available, defaulting to319- given AuthObject.320- """321-322- return _get_autoauth(url) if not auth else auth323-324-325-def _get_autoauth(url):326- """Returns registered AuthObject for given url if available."""327-328- for (autoauth_url, auth) in AUTOAUTHS:329- if autoauth_url in url:330- return auth331-332- return None333-334-420 class RequestException(Exception):421 """There was an ambiguous exception that occured while handling your422 request."""423 8 unmodified linesmodified:README.rst+1 added-28 removed
36 unmodified lines37 38 39 Uh oh, we're not authorized! Let's add authentication. ::40 41- >>> conv_auth = ('requeststest', 'requeststest')41+ >>> conv_auth = requests.AuthObject('requeststest', 'requeststest')42 >>> r = requests.get('https://convore.com/api/account/verify.json', auth=conv_auth)43 44 >>> r.status_code45 20035 unmodified lines81 DELETE Requests82 >>> request.delete(url, params={}, headers={}, cookies=None, auth=None)83 <request object>84 85-**AsyncRequests:**85 87-All request functions return a Response object (see below).88-89-If a {filename: fileobject} dictionary is passed in (files=...), a multipart_encode upload will be performed.90-If CookieJar object is is passed in (cookies=...), the cookies will be sent with the request.91-92- GET Requests93- >>> request.async.get(url, params={}, headers={}, cookies=None, auth=None)94- <request object>95-96- HEAD Requests97- >>> request.async.head(url, params={}, headers={}, cookies=None, auth=None)98- <request object>99-100- PUT Requests101- >>> request.async.put(url, data='', headers={}, files={}, cookies=None, auth=None)102- <request object>103-104- POST Requests105- >>> request.async.post(url, data={}, headers={}, files={}, cookies=None, auth=None)106- <request object>107-108- DELETE Requests109- >>> request.async.delete(url, params={}, headers={}, cookies=None, auth=None)110- <request object>111-112-86 **Responses:**87 88 Response.status_code:89 (Integer) Received HTTP Status Code Response60 unmodified linesmodified:test_requests.py+1 added-3 removed
40 unmodified lines41 r = requests.get(url, auth=auth)42 43 self.assertEqual(r.status_code, 200)44 45- requests.add_autoauth(url, auth)46-45 r = requests.get(url)46 self.assertEqual(r.status_code, 200)47 48 # reset auto authentication51- requests.AUTOAUTHS = []49+ requests.auth_manager.empty()50 51 def test_POSTBIN_GET_POST_FILES(self):52 bin = requests.get('http://www.postbin.org/')53 self.assertEqual(bin.status_code, 200)29 unmodified lines