Skip to content
Myr

Merge branch 'develop'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kenneth Reitz · committed by Kenneth Reitz · parents 42b33ae, ee36baf · Browse files · 14 files+161 added−90 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

14 files+161 added−90 removed

  • other:+161 added−90 removed

14 files+161 added−90 removed

modified:docs/_templates/sidebarintro.html+17 added-1 removed
modified:docs/_templates/sidebarlogo.html+14 added
modified:docs/_themes/kr/layout.html+11 added
modified:docs/user/advanced.rst+17 added-16 removed
209 unmodified lines
210---------------------211212Requests allows you to use specify your own authentication mechanism.213214When you pass our authentication tuple to a request method, the first215string is the type of authentication. 'basic' is inferred if none is216provided.214Any callable which is passed as the ``auth`` argument to a request method will215have the opportunity to modify the request before it is dispatched.216218You can pass in a callable object instead of a string for the first item219in the tuple, and it will be used in place of the built in authentication220callbacks.217Authentication implementations are subclasses of ``requests.auth.AuthBase``,218and are easy to define. Requests provides two common authentication scheme219implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.220221Let's pretend that we have a web service that will only respond if the222``X-Pizza`` header is set to a password value. Unlikely, but just go with it.223225We simply need to define a callback function that will be used to update the226Request object, right before it is dispatched.227224::225230 def pizza_auth(r, username):231 """Attaches HTTP Pizza Authentication to the given Request object.232 """233 r.headers['X-Pizza'] = username226 from requests.auth import AuthBase227 class PizzaAuth(AuthBase):228 """Attaches HTTP Pizza Authentication to the given Request object."""229 def __init__(self, username):230 # setup any auth-related data here231 self.username = username232 233 def __call__(self, r):234 # modify and return the request235 r.headers['X-Pizza'] = self.username236 return r237235 return r236238Then, we can make a request using our Pizza Auth::239239 >>> requests.get('http://pizzabin.org/admin', auth=(pizza_auth, 'kenneth'))240 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))241 <Response [200]>242243244Verbose Logging
11 unmodified lines
modified:docs/user/quickstart.rst+18 added-5 removed
263 unmodified lines
264authentication, but the most common is HTTP Basic Auth.265266Making requests with Basic Auth is extremely simple::267268 >>> from requests.auth import HTTPBasicAuth269 >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))270 <Response [200]>271272Due to the prevalence of HTTP Basic Auth, requests provides a shorthand for273this authentication method::274275 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))276 <Response [200]>277271OAuth Authentication272--------------------278Providing the credentials as a tuple in this fashion is functionally equivalent279to the ``HTTPBasicAuth`` example above.280274Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for275establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.281282Digest Authentication283---------------------284285Another popular form of web service protection is Digest Authentication::286287 >>> from requests.auth import HTTPDigestAuth288 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'283 >>> requests.get(url, auth=('digest', 'user', 'pass'))289 >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))290 <Response [200]>291292293OAuth Authentication294--------------------295296Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for297establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.298299300Redirection and History301-----------------------302303Requests will automatically perform location redirection while using impodotent methods.
66 unmodified lines
modified:requests/__init__.py+2 added-2 removed
13 unmodified lines
1415"""1617__title__ = 'requests'18__version__ = '0.8.2'19__build__ = 0x00080218__version__ = '0.8.3'19__build__ = 0x00080320__author__ = 'Kenneth Reitz'21__license__ = 'ISC'22__copyright__ = 'Copyright 2011 Kenneth Reitz'23
10 unmodified lines
modified:requests/api.py+4 added-2 removed
9 unmodified lines
10:license: ISC, see LICENSE for more details.1112"""1314from .sessions import session14from . import sessions151617def request(method, url,18 params=None,
7 unmodified lines
26 proxies=None,27 hooks=None,28 return_response=True,29 prefetch=False,30 session=None,31 config=None):32 """Constructs and sends a :class:`Request <Request>`.33 Returns :class:`Response <Response>` object.34
8 unmodified lines
43 :param timeout: (optional) Float describing the timeout of the request.44 :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.45 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.46 :param return_response: (optional) If False, an un-sent Request object will returned.47 :param session: (optional) A :class:`Session` object to be used for the request.48 :param config: (optional) A configuration dictionary.49 """5049 s = session()51 s = session or sessions.session()52 return s.request(53 method=method,54 url=url,55 params=params,
90 unmodified lines
modified:requests/async.py+2 added
69 unmodified lines
70 :param prefetch: If False, the content will not be downloaded immediately.71 :param size: Specifies the number of requests to make at a time. If None, no throttling occurs.72 """7374 requests = list(requests)7576 if size:77 pool = Pool(size)78 pool.map(send, requests)79 pool.join()
12 unmodified lines
modified:requests/auth.py+25 added-47 removed
14 unmodified lines
1516from .utils import randombytes, parse_dict_header171819def http_basic(r, username, password):20 """Attaches HTTP Basic Authentication to the given Request object.21 Arguments should be considered non-positional.19class AuthBase(object):20 """Base class that all auth implementations derive from"""2123 """24 username = str(username)25 password = str(password)22 def __call__(self, r):23 raise NotImplementedError('Auth hooks must be callable.')2427 auth_s = b64encode('%s:%s' % (username, password))28 r.headers['Authorization'] = ('Basic %s' % auth_s)2530 return r26class HTTPBasicAuth(AuthBase):27 """Attaches HTTP Basic Authentication to the given Request object."""28 def __init__(self, username, password):29 self.username = str(username)30 self.password = str(password)3132 def __call__(self, r):33 auth_s = b64encode('%s:%s' % (self.username, self.password))34 r.headers['Authorization'] = ('Basic %s' % auth_s)35 return r3633def http_digest(r, username, password):34 """Attaches HTTP Digest Authentication to the given Request object.35 Arguments should be considered non-positional.36 """3738class HTTPDigestAuth(AuthBase):39 """Attaches HTTP Digest Authentication to the given Request object."""40 def __init__(self, username, password):41 self.username = username42 self.password = password4338 def handle_401(r):44 def handle_401(self, r):45 """Takes the given response and tries digest-auth, if needed."""4647 s_auth = r.headers.get('www-authenticate', '')48
26 unmodified lines
75 entdig = None76 p_parsed = urlparse(r.request.url)77 path = p_parsed.path + p_parsed.query7873 A1 = "%s:%s:%s" % (username, realm, password)79 A1 = "%s:%s:%s" % (self.username, realm, self.password)80 A2 = "%s:%s" % (r.request.method, path)8182 if qop == 'auth':83 if nonce == last_nonce:
16 unmodified lines
100 return None101102 # XXX should the partial digests be encoded too?103 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \98 'response="%s"' % (username, realm, nonce, path, respdig)104 'response="%s"' % (self.username, realm, nonce, path, respdig)105 if opaque:106 base += ', opaque="%s"' % opaque107 if entdig:108 base += ', digest="%s"' % entdig109 base += ', algorithm="%s"' % algorithm110 if qop:111 base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)112107113 r.request.headers['Authorization'] = 'Digest %s' % (base)114 r.request.send(anyway=True)115 _r = r.request.response116 _r.history.append(r)
1 unmodified line
118 return _r119120 return r121117 r.hooks['response'] = handle_401118 return r119120121def dispatch(t):122 """Given an auth tuple, return an expanded version."""123124 if not t:125 return t126 else:127 t = list(t)128129 # Make sure they're passing in something.130 assert len(t) >= 2131132 # If only two items are passed in, assume HTTPBasic.133 if (len(t) == 2):134 t.insert(0, 'basic')135136 # Allow built-in string referenced auths.137 if isinstance(t[0], basestring):138 if t[0] in ('basic', 'forced_basic'):139 t[0] = http_basic140 elif t[0] in ('digest',):141 t[0] = http_digest142143 # Return a custom callable.144 return (t[0], tuple(t[1:]))145146122 def __call__(self, r):123 r.hooks['response'] = self.handle_401124 return r
modified:requests/models.py+12 added-12 removed
11 unmodified lines
1213from urlparse import urlparse, urlunparse, urljoin, urlsplit14from datetime import datetime1516from .auth import dispatch as auth_dispatch16from .hooks import dispatch_hook17from .structures import CaseInsensitiveDict18from .status_codes import codes19from .packages import oreos20from .auth import HTTPBasicAuth21from .packages.urllib3.exceptions import MaxRetryError22from .packages.urllib3.exceptions import SSLError as _SSLError23from .packages.urllib3.exceptions import HTTPError as _HTTPError24from .packages.urllib3 import connectionpool, poolmanager
72 unmodified lines
97 #: :class:`Response <Response>` instance, containing98 #: content and metadata of HTTP Response, once :attr:`sent <send>`.99 self.response = Response()100101 #: Authentication tuple to attach to :class:`Request <Request>`.102 self._auth = auth103 self.auth = auth_dispatch(auth)101 #: Authentication tuple or object to attach to :class:`Request <Request>`.102 self.auth = auth103104 #: CookieJar to attach to :class:`Request <Request>`.105 self.cookies = dict(cookies or [])106
122 unmodified lines
229 headers=headers,230 files=self.files,231 method=method,232 params=self.session.params,234 auth=self._auth,233 auth=self.auth,234 cookies=cookies,235 redirect=True,236 config=self.config,237 timeout=self.timeout,
104 unmodified lines
342 :param anyway: If True, request will be sent, even if it has343 already been sent.344 """345346 # Build the URL347 url = self.full_url348349 # Logging350 if self.config.get('verbose'):351 self.config.get('verbose').write('%s %s %s\n' % (350 datetime.now().isoformat(), self.method, self.url352 datetime.now().isoformat(), self.method, url353 ))354353 # Build the URL354 url = self.full_url355355 # Nottin' on you.356 body = None357 content_type = None358
31 unmodified lines
390 # Add content-type if it wasn't explicitly provided.391 if (content_type) and (not 'content-type' in self.headers):392 self.headers['Content-Type'] = content_type393395394 if self.auth:397 auth_func, auth_args = self.auth395 if isinstance(self.auth, tuple) and len(self.auth) == 2:396 # special-case basic HTTP auth397 self.auth = HTTPBasicAuth(*self.auth)398399 # Allow auth to make its changes.400 r = auth_func(self, *auth_args)400 r = self.auth(self)401402 # Update self to reflect the auth changes.403 self.__dict__.update(r.__dict__)404
231 unmodified lines
modified:AUTHORS.rst+3 added-1 removed
58 unmodified lines
59- Joseph McCullough60- Juergen Brendel61- Juan Riaza62- Ryan Kelly63- Rolando Espinoza La fuente63- Rolando Espinoza La fuente64- Robert Gieseke65- Idan Gazit
modified:HISTORY.rst+7 added
1History2-------340.8.3 (2011-11-27)5++++++++++++++++++67* Converted auth system to use simpler callable objects.8* New session parameter to API methods.9* Display full URL while logging.10110.8.2 (2011-11-19)12++++++++++++++++++1314* New unicode decoding system, based on overridable `Response.encoding`.
262 unmodified lines
modified:setup.py+2 added-1 removed
35 unmodified lines
36 url='http://python-requests.org',37 packages= [38 'requests',39 'requests.packages',40 'requests.packages.urllib3'40 'requests.packages.urllib3',41 'requests.packages.oreos'42 ],43 install_requires=required,44 license='ISC',45 classifiers=(
12 unmodified lines
modified:test_requests.py+27 added-3 removed
8 unmodified lines
910import requests11import envoy12from requests import HTTPError13from requests.auth import HTTPBasicAuth, HTTPDigestAuth1415try:16 import omnijson as json17except ImportError:
122 unmodified lines
140 r = requests.patch(httpbin('patch'))141 self.assertEqual(r.status_code, 200)142143143 def test_BASICAUTH_HTTP_200_OK_GET(self):144 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):145146 for service in SERVICES:147148 auth = ('user', 'pass')
10 unmodified lines
159 r = s.get(url)160 self.assertEqual(r.status_code, 200)161162163 def test_BASICAUTH_HTTP_200_OK_GET(self):164165 for service in SERVICES:166167 auth = HTTPBasicAuth('user', 'pass')168 url = service('basic-auth', 'user', 'pass')169170 r = requests.get(url, auth=auth)171 self.assertEqual(r.status_code, 200)172173 auth = ('user', 'pass')174 r = requests.get(url, auth=auth)175 self.assertEqual(r.status_code, 200)176177 r = requests.get(url)178 self.assertEqual(r.status_code, 401)179180181 s = requests.session(auth=auth)182 r = s.get(url)183 self.assertEqual(r.status_code, 200)184185186 def test_DIGESTAUTH_HTTP_200_OK_GET(self):187188 for service in SERVICES:189166 auth = ('digest', 'user', 'pass')190 auth = HTTPDigestAuth('user', 'pass')191 url = service('digest-auth', 'auth', 'user', 'pass')192193 r = requests.get(url, auth=auth)194 self.assertEqual(r.status_code, 200)
98 unmodified lines
293294295 def test_httpauth_recursion(self):296273 http_auth = ('user', 'BADpass')297 http_auth = HTTPBasicAuth('user', 'BADpass')298299 for service in SERVICES:300 r = requests.get(service('basic-auth', 'user', 'pass'), auth=http_auth)301 self.assertEquals(r.status_code, 401)
281 unmodified lines