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
Provenance
- Commit
d1dfa02- Tree
2ceb86d- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
42b33ae- Parent 2
ee36baf
14 files changed+161 added−90 removed
modified:docs/_templates/sidebarintro.html+17 added-1 removed
3 unmodified lines45678910111213141516171819202122232425262728293031322 unmodified lines353637382339404142433 unmodified lines </a></p>
<p> <iframe src="http://markdotto.github.com/github-buttons/github-btn.html?user=kennethreitz&repo=requests&type=watch&count=true&size=large" allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px"></iframe></p>
<p> Requests is an elegant and simple HTTP library for Python, built for human beings. You are currently looking at the documentation of the development release.</p>
<h3>Support Requests</h3><p> If you love Requests, consider making a small donation <a href="https://flattr.com/thing/442264/Requests">on Flattr</a>:</p><p> <a class="FlattrButton" style="display:none;" rev="flattr;button:compact;" href="http://docs.python-requests.org/"></a> <noscript><a href="http://flattr.com/thing/442264/Requests" target="_blank"> <img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
<h3>Feedback</h3><p> Feedback is greatly appreciated. If you have any questions, comments, random praise, or anonymous threats, <a href="mailto:me@kennethreitz.com">2 unmodified lines
<h3>Useful Links</h3><ul> <li><a href="http://python-requests.org/">The Requests Website</a></li> <li><a href="http://pypi.python.org/pypi/requests">Requests @ PyPI</a></li> <li><a href="http://github.com/kennethreitz/requests">Requests @ GitHub</a></li> <li><a href="https://flattr.com/thing/442264/Requests">Requests @ Flattr</a></li> <li><a href="http://github.com/kennethreitz/requests/issues">Issue Tracker</a></li></ul>modified:docs/_templates/sidebarlogo.html+14 added
12345678910111213141516171819202122232425<p class="logo"> <a href="{{ pathto(master_doc) }}"> <img class="logo" src="{{ pathto('_static/requests-sidebar.png', 1) }}" alt="Logo"/> </a></p><p><iframe src="http://markdotto.github.com/github-buttons/github-btn.html?user=kennethreitz&repo=requests&type=watch&count=true&size=large" allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px"></iframe></p>
<p> Requests is an elegant and simple HTTP library for Python, built for human beings. You are currently looking at the documentation of the development release.</p>
<h3>Support Requests</h3><p> If you love Requests, consider making a small donation <a href="https://flattr.com/thing/442264/Requests">on Flattr</a>:</p><p> <a class="FlattrButton" style="display:none;" rev="flattr;button:compact;" href="http://docs.python-requests.org/"></a> <noscript><a href="http://flattr.com/thing/442264/Requests" target="_blank"> <img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>No newline at end of fileNo newline at end of filemodified:docs/_themes/kr/layout.html+11 added
13 unmodified lines1415161718192021222324252627282930313225 unmodified lines13 unmodified lines <a href="https://github.com/kennethreitz/requests" class="github"> <img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" class="github"/> </a> <script type="text/javascript"> /* <![CDATA[ */ (function() { var s = document.createElement('script'), t = document.getElementsByTagName('script')[0]; s.type = 'text/javascript'; s.async = true; s.src = 'http://api.flattr.com/js/0.6/load.js?mode=auto'; t.parentNode.insertBefore(s, t); })(); /* ]]> */ </script> <script type="text/javascript">
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-8742933-11']); _gaq.push(['_setDomainName', 'none']);25 unmodified linesmodified:docs/user/advanced.rst+17 added-16 removed
209 unmodified lines210 ---------------------211 212 Requests allows you to use specify your own authentication mechanism.213 214-When you pass our authentication tuple to a request method, the first215-string is the type of authentication. 'basic' is inferred if none is216-provided.214+Any callable which is passed as the ``auth`` argument to a request method will215+have the opportunity to modify the request before it is dispatched.216 218-You can pass in a callable object instead of a string for the first item219-in the tuple, and it will be used in place of the built in authentication220-callbacks.217+Authentication implementations are subclasses of ``requests.auth.AuthBase``,218+and are easy to define. Requests provides two common authentication scheme219+implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.220 221 Let'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.223 225-We simply need to define a callback function that will be used to update the226-Request object, right before it is dispatched.227-224 ::225 230- 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 r237 235- return r236-238 Then, we can make a request using our Pizza Auth::239 239- >>> requests.get('http://pizzabin.org/admin', auth=(pizza_auth, 'kenneth'))240+ >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))241 <Response [200]>242 243 244 Verbose Logging11 unmodified linesmodified:docs/user/quickstart.rst+18 added-5 removed
263 unmodified lines264 authentication, but the most common is HTTP Basic Auth.265 266 Making requests with Basic Auth is extremely simple::267 268+ >>> from requests.auth import HTTPBasicAuth269+ >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))270+ <Response [200]>271+272+Due to the prevalence of HTTP Basic Auth, requests provides a shorthand for273+this authentication method::274+275 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))276 <Response [200]>277 271-OAuth Authentication272---------------------278+Providing the credentials as a tuple in this fashion is functionally equivalent279+to the ``HTTPBasicAuth`` example above.280 274-Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for275-establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.281 282 Digest Authentication283 ---------------------284 285 Another popular form of web service protection is Digest Authentication::286 287+ >>> 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]>291 292 293+OAuth Authentication294+--------------------295+296+Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for297+establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.298+299+300 Redirection and History301 -----------------------302 303 Requests will automatically perform location redirection while using impodotent methods.66 unmodified linesmodified:requests/__init__.py+2 added-2 removed
13 unmodified lines14 15 """16 17 __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 linesmodified:requests/api.py+4 added-2 removed
9 unmodified lines10 :license: ISC, see LICENSE for more details.11 12 """13 14-from .sessions import session14+from . import sessions15 16 17 def request(method, url,18 params=None,7 unmodified lines26 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 lines43 :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 """50 49- s = session()51+ s = session or sessions.session()52 return s.request(53 method=method,54 url=url,55 params=params,90 unmodified linesmodified:requests/async.py+2 added
69 unmodified lines70 :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 """73 74+ requests = list(requests)75+76 if size:77 pool = Pool(size)78 pool.map(send, requests)79 pool.join()12 unmodified linesmodified:requests/auth.py+25 added-47 removed
14 unmodified lines15 16 from .utils import randombytes, parse_dict_header17 18 19-def http_basic(r, username, password):20- """Attaches HTTP Basic Authentication to the given Request object.21- Arguments should be considered non-positional.19+class AuthBase(object):20+ """Base class that all auth implementations derive from"""21 23- """24- username = str(username)25- password = str(password)22+ def __call__(self, r):23+ raise NotImplementedError('Auth hooks must be callable.')24 27- auth_s = b64encode('%s:%s' % (username, password))28- r.headers['Authorization'] = ('Basic %s' % auth_s)25 30- return r26+class 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)31 32+ def __call__(self, r):33+ auth_s = b64encode('%s:%s' % (self.username, self.password))34+ r.headers['Authorization'] = ('Basic %s' % auth_s)35+ return r36 33-def http_digest(r, username, password):34- """Attaches HTTP Digest Authentication to the given Request object.35- Arguments should be considered non-positional.36- """37 38+class HTTPDigestAuth(AuthBase):39+ """Attaches HTTP Digest Authentication to the given Request object."""40+ def __init__(self, username, password):41+ self.username = username42+ self.password = password43+38- def handle_401(r):44+ def handle_401(self, r):45 """Takes the given response and tries digest-auth, if needed."""46 47 s_auth = r.headers.get('www-authenticate', '')48 26 unmodified lines75 entdig = None76 p_parsed = urlparse(r.request.url)77 path = p_parsed.path + p_parsed.query78 73- 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)81 82 if qop == 'auth':83 if nonce == last_nonce:16 unmodified lines100 return None101 102 # 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)112 107-113 r.request.headers['Authorization'] = 'Digest %s' % (base)114 r.request.send(anyway=True)115 _r = r.request.response116 _r.history.append(r)1 unmodified line118 return _r119 120 return r121 117- r.hooks['response'] = handle_401118- return r119-120-121-def dispatch(t):122- """Given an auth tuple, return an expanded version."""123-124- if not t:125- return t126- else:127- t = list(t)128-129- # Make sure they're passing in something.130- assert len(t) >= 2131-132- # If only two items are passed in, assume HTTPBasic.133- if (len(t) == 2):134- t.insert(0, 'basic')135-136- # 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_digest142-143- # Return a custom callable.144- return (t[0], tuple(t[1:]))145-146-122+ def __call__(self, r):123+ r.hooks['response'] = self.handle_401124+ return rmodified:requests/models.py+12 added-12 removed
11 unmodified lines12 13 from urlparse import urlparse, urlunparse, urljoin, urlsplit14 from datetime import datetime15 16-from .auth import dispatch as auth_dispatch16 from .hooks import dispatch_hook17 from .structures import CaseInsensitiveDict18 from .status_codes import codes19 from .packages import oreos20+from .auth import HTTPBasicAuth21 from .packages.urllib3.exceptions import MaxRetryError22 from .packages.urllib3.exceptions import SSLError as _SSLError23 from .packages.urllib3.exceptions import HTTPError as _HTTPError24 from .packages.urllib3 import connectionpool, poolmanager72 unmodified lines97 #: :class:`Response <Response>` instance, containing98 #: content and metadata of HTTP Response, once :attr:`sent <send>`.99 self.response = Response()100 101- #: 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 = auth103 104 #: CookieJar to attach to :class:`Request <Request>`.105 self.cookies = dict(cookies or [])106 122 unmodified lines229 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 lines342 :param anyway: If True, request will be sent, even if it has343 already been sent.344 """345 346+ # Build the URL347+ url = self.full_url348+349 # 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 ))354 353- # Build the URL354- url = self.full_url355-355 # Nottin' on you.356 body = None357 content_type = None358 31 unmodified lines390 # 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_type393 395-394 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)398 399 # Allow auth to make its changes.400- r = auth_func(self, *auth_args)400+ r = self.auth(self)401 402 # Update self to reflect the auth changes.403 self.__dict__.update(r.__dict__)404 231 unmodified linesmodified:AUTHORS.rst+3 added-1 removed
58 unmodified lines59 - Joseph McCullough60 - Juergen Brendel61 - Juan Riaza62 - Ryan Kelly63-- Rolando Espinoza La fuente63+- Rolando Espinoza La fuente64+- Robert Gieseke65+- Idan Gazitmodified:HISTORY.rst+7 added
1 History2 -------3 4+0.8.3 (2011-11-27)5+++++++++++++++++++6+7+* Converted auth system to use simpler callable objects.8+* New session parameter to API methods.9+* Display full URL while logging.10+11 0.8.2 (2011-11-19)12 ++++++++++++++++++13 14 * New unicode decoding system, based on overridable `Response.encoding`.262 unmodified linesmodified:setup.py+2 added-1 removed
35 unmodified lines36 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 linesmodified:test_requests.py+27 added-3 removed
8 unmodified lines9 10 import requests11 import envoy12 from requests import HTTPError13+from requests.auth import HTTPBasicAuth, HTTPDigestAuth14 15 try:16 import omnijson as json17 except ImportError:122 unmodified lines140 r = requests.patch(httpbin('patch'))141 self.assertEqual(r.status_code, 200)142 143 143- def test_BASICAUTH_HTTP_200_OK_GET(self):144+ def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):145 146 for service in SERVICES:147 148 auth = ('user', 'pass')10 unmodified lines159 r = s.get(url)160 self.assertEqual(r.status_code, 200)161 162 163+ def test_BASICAUTH_HTTP_200_OK_GET(self):164+165+ for service in SERVICES:166+167+ auth = HTTPBasicAuth('user', 'pass')168+ url = service('basic-auth', 'user', 'pass')169+170+ r = requests.get(url, auth=auth)171+ self.assertEqual(r.status_code, 200)172+173+ auth = ('user', 'pass')174+ r = requests.get(url, auth=auth)175+ self.assertEqual(r.status_code, 200)176+177+ r = requests.get(url)178+ self.assertEqual(r.status_code, 401)179+180+181+ s = requests.session(auth=auth)182+ r = s.get(url)183+ self.assertEqual(r.status_code, 200)184+185+186 def test_DIGESTAUTH_HTTP_200_OK_GET(self):187 188 for service in SERVICES:189 166- auth = ('digest', 'user', 'pass')190+ auth = HTTPDigestAuth('user', 'pass')191 url = service('digest-auth', 'auth', 'user', 'pass')192 193 r = requests.get(url, auth=auth)194 self.assertEqual(r.status_code, 200)98 unmodified lines293 294 295 def test_httpauth_recursion(self):296 273- http_auth = ('user', 'BADpass')297+ http_auth = HTTPBasicAuth('user', 'BADpass')298 299 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