Skip to content
Myr

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

4 files+158 added−102 removed

modified:requests/async.py+1 added-1 removed
31 unmodified lines
32 raise ImportError('No Async adaptations of urllib2 found!')3334from .core import *3536__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__ = 0x000001
3 unmodified lines
modified:requests/core.py+155 added-70 removed
16 unmodified lines
1718from .packages.poster.encode import multipart_encode19from .packages.poster.streaminghttp import register_openers2021__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'293031AUTOAUTHS = []3230class _Request(urllib2.Request):31 """Hidden wrapper around the urllib2.Request object. Allows for manual32 setting of HTTP methods.33 """
31 unmodified lines
65 self.data = data6667 self.response = Response()6869 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 lines
94 """Creates appropriate opener object for urllib2."""9596 _handlers = []9797 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)103101 authr.add_password(None, self.url, self.auth[0], self.auth[1])102 auth_handler = urllib2.HTTPBasicAuthHandler(authr)104 _handlers.append(self.auth.handler)105104 _handlers.append(auth_handler)105106 if self.cookiejar:107 cookie_handler = urllib2.HTTPCookieProcessor(cookiejar)108 _handlers.append(cookie_handler)109106 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.open112112 else:113 return urllib2.urlopen114115116 def _build_response(self, resp):117 """Build internal Response object from given response."""118119 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.url123124
35 unmodified lines
160 self.response.error = why161 else:162 self._build_response(resp)163 self.response.ok = True164165 self.response.cached = False165 self.response.cached = False166 else:167 self.response.cached = True168169
28 unmodified lines
198 """Raises stored HTTPError if one exists."""199 if self.error:200 raise self.error201202class AuthManager(object):203 def __new__(cls):204 singleton = cls.__dict__.get('__singleton__')205 if singleton is not None:206 return singleton207208 cls.__singleton__ = singleton = object.__new__(cls)209210 return singleton211212 def __init__(self):213 self.passwd = {}214 self._auth = {}215216 def add_auth(self, uri, auth):217 uri = self.reduce_uri(uri, False)218 self._auth[uri] = auth219220 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)228229 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 authinfo235236 return (None, None)237238 def get_auth(self, uri):239 uri = self.reduce_uri(uri, False)240 return self._auth.get(uri, None)241242 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, path264265 def is_suburi(self, base, test):266 """Check if test is below base in a URI tree267268 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 False278279 def empty(self):280 self.passwd = {}281282 def remove(self, uri, realm=None):283 # uri could be a single URI or a sequence284 if isinstance(uri, basestring):285 uri = [uri]286287 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]290291 def __contains__(self, uri):292 # uri could be a single URI or a sequence293 if isinstance(uri, basestring):294 uri = [uri]295296 uri = tuple([self.reduce_uri(u, False) for u in uri])297298 if uri in self.passwd:299 return True300301 return False302303auth_manager = AuthManager()304305306class 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.311312 :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 """317318 _handlers = {319 'basic': urllib2.HTTPBasicAuthHandler,320 'digest': urllib2.HTTPDigestAuthHandler,321 'proxy_basic': urllib2.ProxyBasicAuthHandler,322 'proxy_digest': urllib2.ProxyDigestAuthHandler323 }324325 def __init__(self, username, password, handler='basic', realm=None):326 self.username = username327 self.password = password328 self.realm = realm329330 self.handler = self._handlers.get(handler.lower(), urllib2.HTTPBasicAuthHandler)331332333def request(method, url, **kwargs):334 """Sends a `method` request. Returns :class:`Response` object.335336 :param method: method for the new :class:`Request` object.
8 unmodified lines
345 data = kwargs.pop('data', {}) or kwargs.pop('params', {})346347 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()351352 return r.response353
6 unmodified lines
360 :param cookies: (optional) CookieJar object to send with the :class:`Request`.361 :param auth: (optional) AuthObject to enable Basic HTTP Auth.362 """363234 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)365366367def head(url, params={}, headers={}, cookies=None, auth=None):368 """Sends a HEAD request. Returns :class:`Response` object.
4 unmodified lines
373 :param cookies: (optional) CookieJar object to send with the :class:`Request`.374 :param auth: (optional) AuthObject to enable Basic HTTP Auth.375 """376248 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)378379380def post(url, data={}, headers={}, files=None, cookies=None, auth=None):381 """Sends a POST request. Returns :class:`Response` object.
5 unmodified lines
387 :param cookies: (optional) CookieJar object to send with the :class:`Request`.388 :param auth: (optional) AuthObject to enable Basic HTTP Auth.389 """390263 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)392393394def put(url, data=b'', headers={}, files={}, cookies=None, auth=None):395 """Sends a PUT request. Returns :class:`Response` object.
5 unmodified lines
401 :param cookies: (optional) CookieJar object to send with the :class:`Request`.402 :param auth: (optional) AuthObject to enable Basic HTTP Auth.403 """404278 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)406407408def delete(url, params={}, headers={}, cookies=None, auth=None):409 """Sends a DELETE request. Returns :class:`Response` object.
4 unmodified lines
414 :param cookies: (optional) CookieJar object to send with the :class:`Request`.415 :param auth: (optional) AuthObject to enable Basic HTTP Auth.416 """417292 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)419295296def 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.301302 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!307308 :param url: Base URL for given AuthObject to auto-activate for.309 :param authobject: AuthObject to auto-activate.310 """311312 global AUTOAUTHS313314 AUTOAUTHS.append((url, authobject))315316317def _detect_auth(url, auth):318 """Returns registered AuthObject for given url if available, defaulting to319 given AuthObject.320 """321322 return _get_autoauth(url) if not auth else auth323324325def _get_autoauth(url):326 """Returns registered AuthObject for given url if available."""327328 for (autoauth_url, auth) in AUTOAUTHS:329 if autoauth_url in url:330 return auth331332 return None333334420class RequestException(Exception):421 """There was an ambiguous exception that occured while handling your422 request."""423
8 unmodified lines
modified:README.rst+1 added-28 removed
36 unmodified lines
373839Uh oh, we're not authorized! Let's add authentication. ::4041 >>> 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)4344 >>> r.status_code45 200
35 unmodified lines
81 DELETE Requests82 >>> request.delete(url, params={}, headers={}, cookies=None, auth=None)83 <request object>8485**AsyncRequests:**8587All request functions return a Response object (see below).8889If a {filename: fileobject} dictionary is passed in (files=...), a multipart_encode upload will be performed.90If CookieJar object is is passed in (cookies=...), the cookies will be sent with the request.9192 GET Requests93 >>> request.async.get(url, params={}, headers={}, cookies=None, auth=None)94 <request object>9596 HEAD Requests97 >>> request.async.head(url, params={}, headers={}, cookies=None, auth=None)98 <request object>99100 PUT Requests101 >>> request.async.put(url, data='', headers={}, files={}, cookies=None, auth=None)102 <request object>103104 POST Requests105 >>> request.async.post(url, data={}, headers={}, files={}, cookies=None, auth=None)106 <request object>107108 DELETE Requests109 >>> request.async.delete(url, params={}, headers={}, cookies=None, auth=None)110 <request object>11111286**Responses:**8788 Response.status_code:89 (Integer) Received HTTP Status Code Response
60 unmodified lines
modified:test_requests.py+1 added-3 removed
40 unmodified lines
41 r = requests.get(url, auth=auth)4243 self.assertEqual(r.status_code, 200)4445 requests.add_autoauth(url, auth)4645 r = requests.get(url)46 self.assertEqual(r.status_code, 200)4748 # reset auto authentication51 requests.AUTOAUTHS = []49 requests.auth_manager.empty()5051 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