Merge remote-tracking branch 'origin/master'
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 538dbae, 5943afa · Browse files · 13 files·+337 added−59 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+337 added−59 removed
- other:+337 added−59 removed
Provenance
- Commit
7430a49- Tree
f15c6f5- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
538dbae- Parent 2
5943afa
13 files changed+337 added−59 removed
modified:docs/community/support.rst+1 added-1 removed
1 unmodified line2 3 Support4 =======5 6-If you have a questions or issues about Requests, there are several options:6+If you have questions or issues about Requests, there are several options:7 8 Send a Tweet9 ------------10 27 unmodified linesmodified:docs/user/authentication.rst+1 added-1 removed
47 unmodified lines48 ----------------------49 50 A common form of authentication for several web APIs is OAuth. The ``requests-oauthlib`` library allows Requests users to easily make OAuth authenticated requests::51 52- >>> import request52+ >>> import requests53 >>> from requests_oauthlib import OAuth154 55 >>> url = 'https://api.twitter.com/1.1/account/verify_credentials.json'56 >>> auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',47 unmodified linesmodified:docs/api.rst+11 added-14 removed
46 unmodified lines47 48 Exceptions49 ~~~~~~~~~~50 51-.. module:: requests51+.. autoexception:: requests.exceptions.RequestException52+.. autoexception:: requests.exceptions.ConnectionError53+.. autoexception:: requests.exceptions.HTTPError54+.. autoexception:: requests.exceptions.URLRequired55+.. autoexception:: requests.exceptions.TooManyRedirects56 53-.. autoexception:: RequestException54-.. autoexception:: ConnectionError55-.. autoexception:: HTTPError56-.. autoexception:: URLRequired57-.. autoexception:: TooManyRedirects57 59-58 Status Code Lookup59 ~~~~~~~~~~~~~~~~~~60 61 .. autofunction:: requests.codes11 unmodified lines73 74 Cookies75 ~~~~~~~76 79-.. autofunction:: dict_from_cookiejar80-.. autofunction:: cookiejar_from_dict81-.. autofunction:: add_dict_to_cookiejar77+.. autofunction:: requests.utils.dict_from_cookiejar78+.. autofunction:: requests.utils.cookiejar_from_dict79+.. autofunction:: requests.utils.add_dict_to_cookiejar80 81 82 Encodings83 ~~~~~~~~~84 87-.. autofunction:: get_encodings_from_content88-.. autofunction:: get_encoding_from_headers89-.. autofunction:: get_unicode_from_response90-.. autofunction:: decode_gzip85+.. autofunction:: requests.utils.get_encodings_from_content86+.. autofunction:: requests.utils.get_encoding_from_headers87+.. autofunction:: requests.utils.get_unicode_from_response88 89 90 Classes91 ~~~~~~~103 unmodified linesmodified:requests/__init__.py+6 added
46 unmodified lines47 __author__ = 'Kenneth Reitz'48 __license__ = 'Apache 2.0'49 __copyright__ = 'Copyright 2013 Kenneth Reitz'50 51+# Attempt to enable urllib3's SNI support, if possible52+try:53+ from requests.packages.urllib3.contrib import pyopenssl54+ pyopenssl.inject_into_urllib3()55+except ImportError:56+ pass57 58 from . import utils59 from .models import Request, Response, PreparedRequest60 from .api import request, get, head, post, patch, put, delete, options17 unmodified linesmodified:requests/models.py+16 added-8 removed
16 unmodified lines17 18 from .auth import HTTPBasicAuth19 from .cookies import cookiejar_from_dict, get_cookie_header20 from .packages.urllib3.filepost import encode_multipart_formdata21+from .packages.urllib3.util import parse_url22 from .exceptions import HTTPError, RequestException, MissingSchema, InvalidURL23 from .utils import (24 guess_filename, get_auth_from_url, requote_uri,25 stream_decode_response_unicode, to_key_val_list, parse_header_links,258 unmodified lines284 except UnicodeDecodeError:285 pass286 287 # Support for unicode domain names and paths.287- scheme, netloc, path, _params, query, fragment = urlparse(url)288+ scheme, auth, host, port, path, query, fragment = parse_url(url)289 290 if not scheme:291 raise MissingSchema("Invalid URL %r: No schema supplied" % url)292 292- if not netloc:293- raise InvalidURL("Invalid URL %t: No netloc supplied" % url)293+ if not host:294+ raise InvalidURL("Invalid URL %t: No host supplied" % url)295 296+ # Only want to apply IDNA to the hostname297 try:296- netloc = netloc.encode('idna').decode('utf-8')298+ host = host.encode('idna').decode('utf-8')299 except UnicodeError:300 raise InvalidURL('URL has an invalid label.')301 302+ # Carefully reconstruct the network location303+ netloc = auth or ''304+ if netloc:305+ netloc += '@'306+ netloc += host307+ if port:308+ netloc += ':' + str(port)309+310 # Bare domains aren't valid URLs.311 if not path:312 path = '/'313 3 unmodified lines317 if isinstance(netloc, str):318 netloc = netloc.encode('utf-8')319 if isinstance(path, str):320 path = path.encode('utf-8')311- if isinstance(_params, str):312- _params = _params.encode('utf-8')321 if isinstance(query, str):322 query = query.encode('utf-8')323 if isinstance(fragment, str):324 fragment = fragment.encode('utf-8')4 unmodified lines329 query = '%s&%s' % (query, enc_params)330 else:331 query = enc_params332 325- url = requote_uri(urlunparse([scheme, netloc, path, _params, query, fragment]))333+ url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))334 self.url = url335 336 def prepare_headers(self, headers):337 """Prepares the given HTTP headers."""315 unmodified lines653 @property654 def links(self):655 """Returns the parsed header links of the response, if any."""656 649- header = self.headers['link']657+ header = self.headers.get('link')658 659 # l = MultiDict()660 l = {}661 25 unmodified linesmodified:requests/sessions.py+9 added-5 removed
9 unmodified lines10 """11 import os12 from datetime import datetime13 14-from .compat import cookielib14+from .compat import cookielib, OrderedDict, urljoin, urlparse15 from .cookies import cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar16 from .models import Request, PreparedRequest17 from .hooks import default_hooks, dispatch_hook18 from .utils import from_key_val_list, default_headers19 from .exceptions import TooManyRedirects, InvalidSchema20 21-from .compat import urlparse, urljoin21 from .adapters import HTTPAdapter22 23 from .utils import requote_uri, get_environ_proxies, get_netrc_auth24 196 unmodified lines221 # Set up a CookieJar to be used by default222 self.cookies = cookiejar_from_dict({})223 224 # Default connection adapters.226- self.adapters = {}227- self.mount('http://', HTTPAdapter())225+ self.adapters = OrderedDict()226 self.mount('https://', HTTPAdapter())227+ self.mount('http://', HTTPAdapter())228 229 def __enter__(self):230 return self231 256 unmodified lines488 for _, v in self.adapters.items():489 v.close()490 491 def mount(self, prefix, adapter):493- """Registers a connection adapter to a prefix."""492+ """Registers a connection adapter to a prefix.493+494+ Adapters are sorted in descending order by key length."""495 self.adapters[prefix] = adapter496+ keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]497+ for key in keys_to_move:498+ self.adapters[key] = self.adapters.pop(key)499 500 def __getstate__(self):501 return dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)502 9 unmodified linesmodified:requests/structures.py+62 added-25 removed
7 unmodified lines8 9 """10 11 import os12+import collections13 from itertools import islice14 15 16 class IteratorProxy(object):16 unmodified lines33 def read(self, n):34 return "".join(islice(self.i, None, n))35 36 36-class CaseInsensitiveDict(dict):37- """Case-insensitive Dictionary37+class CaseInsensitiveDict(collections.MutableMapping):38+ """39+ A case-insensitive ``dict``-like object.40 41+ Implements all methods and operations of42+ ``collections.MutableMapping`` as well as dict's ``copy``. Also43+ provides ``lower_items``.44+45+ All keys are expected to be strings. The structure remembers the46+ case of the last key to be set, and ``iter(instance)``,47+ ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``48+ will contain case-sensitive keys. However, querying and contains49+ testing is case insensitive:50+51+ cid = CaseInsensitiveDict()52+ cid['Accept'] = 'application/json'53+ cid['aCCEPT'] == 'application/json' # True54+ list(cid) == ['Accept'] # True55+56 For example, ``headers['content-encoding']`` will return the40- value of a ``'Content-Encoding'`` response header."""57+ value of a ``'Content-Encoding'`` response header, regardless58+ of how the header name was originally stored.59 42- @property43- def lower_keys(self):44- if not hasattr(self, '_lower_keys') or not self._lower_keys:45- self._lower_keys = dict((k.lower(), k) for k in list(self.keys()))46- return self._lower_keys60+ If the constructor, ``.update``, or equality comparison61+ operations are given keys that have equal ``.lower()``s, the62+ behavior is undefined.63 48- def _clear_lower_keys(self):49- if hasattr(self, '_lower_keys'):50- self._lower_keys.clear()64+ """65+ def __init__(self, data=None, **kwargs):66+ self._store = dict()67+ if data is None:68+ data = {}69+ self.update(data, **kwargs)70 71 def __setitem__(self, key, value):53- dict.__setitem__(self, key, value)54- self._clear_lower_keys()72+ # Use the lowercased key for lookups, but store the actual73+ # key alongside the value.74+ self._store[key.lower()] = (key, value)75 76+ def __getitem__(self, key):77+ return self._store[key.lower()][1]78+79 def __delitem__(self, key):57- dict.__delitem__(self, self.lower_keys.get(key.lower(), key))58- self._lower_keys.clear()80+ del self._store[key.lower()]81 60- def __contains__(self, key):61- return key.lower() in self.lower_keys82+ def __iter__(self):83+ return (casedkey for casedkey, mappedvalue in self._store.values())84 63- def __getitem__(self, key):64- # We allow fall-through here, so values default to None65- if key in self:66- return dict.__getitem__(self, self.lower_keys[key.lower()])85+ def __len__(self):86+ return len(self._store)87 68- def get(self, key, default=None):69- if key in self:70- return self[key]88+ def lower_items(self):89+ """Like iteritems(), but with all lowercase keys."""90+ return (91+ (lowerkey, keyval[1])92+ for (lowerkey, keyval)93+ in self._store.items()94+ )95+96+ def __eq__(self, other):97+ if isinstance(other, collections.Mapping):98+ other = CaseInsensitiveDict(other)99 else:72- return default100+ return NotImplemented101+ # Compare insensitively102+ return dict(self.lower_items()) == dict(other.lower_items())103 104+ # Copy is required105+ def copy(self):106+ return CaseInsensitiveDict(self._store.values())107 108+ def __repr__(self):109+ return '%s(%r)' % (self.__class__.__name__, dict(self.items()))110+111+112 class LookupDict(dict):113 """Dictionary lookup object."""114 115 def __init__(self, name=None):13 unmodified linesmodified:requests/utils.py+3 added-2 removed
21 unmodified lines22 from . import certs23 from .compat import parse_http_list as _parse_list_header24 from .compat import quote, urlparse, bytes, str, OrderedDict, urlunparse25 from .cookies import RequestsCookieJar, cookiejar_from_dict26+from .structures import CaseInsensitiveDict27 28 _hush_pyflakes = (RequestsCookieJar,)29 30 NETRC_FILES = ('.netrc', '_netrc')418 unmodified lines449 '%s/%s' % (p_system, p_release)])450 451 452 def default_headers():452- return {453+ return CaseInsensitiveDict({454 'User-Agent': default_user_agent(),455 'Accept-Encoding': ', '.join(('gzip', 'deflate', 'compress')),456 'Accept': '*/*'456- }457+ })458 459 460 def parse_header_links(value):461 """Return a dict of parsed link headers proxies.89 unmodified linesmodified:.gitignore+1 added
3 unmodified lines4 nosetests.xml5 junit-report.xml6 pylint.txt7 toy.py8+tox.ini9 violations.pyflakes.txt10 cover/11 build/12 docs/_build11 unmodified linesmodified:AUTHORS.rst+4 added
122 unmodified lines123 - Denis Ryzhkov <denisr@denisr.com>124 - Wilfred Hughes <me@wilfred.me.uk> @dontYetKnow125 - Dmitry Medvinsky <me@dmedvinsky.name>126 - Bryce Boe <bbzbryce@gmail.com> @bboe127+- Colin Dunklau <colin.dunklau@gmail.com> @cdunklau128+- Hugo Osvaldo Barrera <hugo@osvaldobarrera.com.ar> @hobarrera129+- Łukasz Langa <lukasz@langa.pl> @llanga130+- Dave Shawley <daveshawley@gmail.com>modified:README.rst+5 added
70 unmodified lines71 72 But, you really shouldn't do that.73 74 75+Documentation76+-------------77 78+Documentation is available at http://docs.python-requests.org/.79+80+81 Contribute82 ----------83 84 #. Check for open issues or open a fresh issue to start a discussion around a feature idea or a bug. There is a Contributor Friendly tag for issues that should be ideal for people who are not very familiar with the codebase yet.6 unmodified linesmodified:setup.py+2 added-3 removed
18 unmodified lines19 'requests.packages',20 'requests.packages.charade',21 'requests.packages.urllib3',22 'requests.packages.urllib3.packages',23+ 'requests.packages.urllib3.contrib',24 'requests.packages.urllib3.packages.ssl_match_hostname'25 ]26 27 requires = []23 unmodified lines51 'Programming Language :: Python',52 'Programming Language :: Python :: 2.6',53 'Programming Language :: Python :: 2.7',54 'Programming Language :: Python :: 3',54- # 'Programming Language :: Python :: 3.0',55- 'Programming Language :: Python :: 3.1',56- 'Programming Language :: Python :: 3.2',55 'Programming Language :: Python :: 3.3',56+57 ),58 )modified:test_requests.py+216 added
9 unmodified lines10 import pickle11 12 import requests13 from requests.auth import HTTPDigestAuth14+from requests.adapters import HTTPAdapter15 from requests.compat import str, cookielib16 from requests.cookies import cookiejar_from_dict17+from requests.structures import CaseInsensitiveDict18 19 try:20 import StringIO21 except ImportError:437 unmodified lines459 460 r = s.send(r.prepare())461 self.assertEqual(r.status_code, 200)462 463+ def test_fixes_1329(self):464+ """465+ Ensure that header updates are done case-insensitively.466+ """467+ s = requests.Session()468+ s.headers.update({'ACCEPT': 'BOGUS'})469+ s.headers.update({'accept': 'application/json'})470+ r = s.get(httpbin('get'))471+ headers = r.request.headers472+ # ASCII encode because of key comparison changes in py3473+ self.assertEqual(474+ headers['accept'.encode('ascii')],475+ 'application/json'476+ )477+ self.assertEqual(478+ headers['Accept'.encode('ascii')],479+ 'application/json'480+ )481+ self.assertEqual(482+ headers['ACCEPT'.encode('ascii')],483+ 'application/json'484+ )485 486+ def test_transport_adapter_ordering(self):487+ s = requests.Session()488+ order = ['https://', 'http://']489+ self.assertEqual(order, list(s.adapters))490+ s.mount('http://git', HTTPAdapter())491+ s.mount('http://github', HTTPAdapter())492+ s.mount('http://github.com', HTTPAdapter())493+ s.mount('http://github.com/about/', HTTPAdapter())494+ order = [495+ 'http://github.com/about/',496+ 'http://github.com',497+ 'http://github',498+ 'http://git',499+ 'https://',500+ 'http://',501+ ]502+ self.assertEqual(order, list(s.adapters))503+ s.mount('http://gittip', HTTPAdapter())504+ s.mount('http://gittip.com', HTTPAdapter())505+ s.mount('http://gittip.com/about/', HTTPAdapter())506+ order = [507+ 'http://github.com/about/',508+ 'http://gittip.com/about/',509+ 'http://github.com',510+ 'http://gittip.com',511+ 'http://github',512+ 'http://gittip',513+ 'http://git',514+ 'https://',515+ 'http://',516+ ]517+ self.assertEqual(order, list(s.adapters))518+ s2 = requests.Session()519+ s2.adapters = {'http://': HTTPAdapter()}520+ s2.mount('https://', HTTPAdapter())521+ self.assertTrue('http://' in s2.adapters)522+ self.assertTrue('https://' in s2.adapters)523+524+ def test_long_authinfo_in_url(self):525+ url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(526+ 'E8A3BE87-9E3F-4620-8858-95478E385B5B',527+ 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',528+ 'exactly-------------sixty-----------three------------characters',529+ )530+ r = requests.Request('GET', url).prepare()531+ self.assertEqual(r.url, url)532+533+534+class TestCaseInsensitiveDict(unittest.TestCase):535+536+ def test_mapping_init(self):537+ cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})538+ self.assertEqual(len(cid), 2)539+ self.assertTrue('foo' in cid)540+ self.assertTrue('bar' in cid)541+542+ def test_iterable_init(self):543+ cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])544+ self.assertEqual(len(cid), 2)545+ self.assertTrue('foo' in cid)546+ self.assertTrue('bar' in cid)547+548+ def test_kwargs_init(self):549+ cid = CaseInsensitiveDict(FOO='foo', BAr='bar')550+ self.assertEqual(len(cid), 2)551+ self.assertTrue('foo' in cid)552+ self.assertTrue('bar' in cid)553+554+ def test_docstring_example(self):555+ cid = CaseInsensitiveDict()556+ cid['Accept'] = 'application/json'557+ self.assertEqual(cid['aCCEPT'], 'application/json')558+ self.assertEqual(list(cid), ['Accept'])559+560+ def test_len(self):561+ cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})562+ cid['A'] = 'a'563+ self.assertEqual(len(cid), 2)564+565+ def test_getitem(self):566+ cid = CaseInsensitiveDict({'Spam': 'blueval'})567+ self.assertEqual(cid['spam'], 'blueval')568+ self.assertEqual(cid['SPAM'], 'blueval')569+570+ def test_fixes_649(self):571+ """__setitem__ should behave case-insensitively."""572+ cid = CaseInsensitiveDict()573+ cid['spam'] = 'oneval'574+ cid['Spam'] = 'twoval'575+ cid['sPAM'] = 'redval'576+ cid['SPAM'] = 'blueval'577+ self.assertEqual(cid['spam'], 'blueval')578+ self.assertEqual(cid['SPAM'], 'blueval')579+ self.assertEqual(list(cid.keys()), ['SPAM'])580+581+ def test_delitem(self):582+ cid = CaseInsensitiveDict()583+ cid['Spam'] = 'someval'584+ del cid['sPam']585+ self.assertFalse('spam' in cid)586+ self.assertEqual(len(cid), 0)587+588+ def test_contains(self):589+ cid = CaseInsensitiveDict()590+ cid['Spam'] = 'someval'591+ self.assertTrue('Spam' in cid)592+ self.assertTrue('spam' in cid)593+ self.assertTrue('SPAM' in cid)594+ self.assertTrue('sPam' in cid)595+ self.assertFalse('notspam' in cid)596+597+ def test_get(self):598+ cid = CaseInsensitiveDict()599+ cid['spam'] = 'oneval'600+ cid['SPAM'] = 'blueval'601+ self.assertEqual(cid.get('spam'), 'blueval')602+ self.assertEqual(cid.get('SPAM'), 'blueval')603+ self.assertEqual(cid.get('sPam'), 'blueval')604+ self.assertEqual(cid.get('notspam', 'default'), 'default')605+606+ def test_update(self):607+ cid = CaseInsensitiveDict()608+ cid['spam'] = 'blueval'609+ cid.update({'sPam': 'notblueval'})610+ self.assertEqual(cid['spam'], 'notblueval')611+ cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})612+ cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})613+ self.assertEqual(len(cid), 2)614+ self.assertEqual(cid['foo'], 'anotherfoo')615+ self.assertEqual(cid['bar'], 'anotherbar')616+617+ def test_update_retains_unchanged(self):618+ cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})619+ cid.update({'foo': 'newfoo'})620+ self.assertEquals(cid['bar'], 'bar')621+622+ def test_iter(self):623+ cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})624+ keys = frozenset(['Spam', 'Eggs'])625+ self.assertEqual(frozenset(iter(cid)), keys)626+627+ def test_equality(self):628+ cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})629+ othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})630+ self.assertEqual(cid, othercid)631+ del othercid['spam']632+ self.assertNotEqual(cid, othercid)633+ self.assertEqual(cid, {'spam': 'blueval', 'eggs': 'redval'})634+635+ def test_setdefault(self):636+ cid = CaseInsensitiveDict({'Spam': 'blueval'})637+ self.assertEqual(638+ cid.setdefault('spam', 'notblueval'),639+ 'blueval'640+ )641+ self.assertEqual(642+ cid.setdefault('notspam', 'notblueval'),643+ 'notblueval'644+ )645+646+ def test_lower_items(self):647+ cid = CaseInsensitiveDict({648+ 'Accept': 'application/json',649+ 'user-Agent': 'requests',650+ })651+ keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())652+ lowerkeyset = frozenset(['accept', 'user-agent'])653+ self.assertEqual(keyset, lowerkeyset)654+655+ def test_preserve_key_case(self):656+ cid = CaseInsensitiveDict({657+ 'Accept': 'application/json',658+ 'user-Agent': 'requests',659+ })660+ keyset = frozenset(['Accept', 'user-Agent'])661+ self.assertEqual(frozenset(i[0] for i in cid.items()), keyset)662+ self.assertEqual(frozenset(cid.keys()), keyset)663+ self.assertEqual(frozenset(cid), keyset)664+665+ def test_preserve_last_key_case(self):666+ cid = CaseInsensitiveDict({667+ 'Accept': 'application/json',668+ 'user-Agent': 'requests',669+ })670+ cid.update({'ACCEPT': 'application/json'})671+ cid['USER-AGENT'] = 'requests'672+ keyset = frozenset(['ACCEPT', 'USER-AGENT'])673+ self.assertEqual(frozenset(i[0] for i in cid.items()), keyset)674+ self.assertEqual(frozenset(cid.keys()), keyset)675+ self.assertEqual(frozenset(cid), keyset)676+677+678 if __name__ == '__main__':679 unittest.main()