Skip to content
Myr

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

13 files+337 added−59 removed

modified:docs/community/support.rst+1 added-1 removed
1 unmodified line
23Support4=======56If you have a questions or issues about Requests, there are several options:6If you have questions or issues about Requests, there are several options:78Send a Tweet9------------10
27 unmodified lines
modified:docs/user/authentication.rst+1 added-1 removed
47 unmodified lines
48----------------------4950A common form of authentication for several web APIs is OAuth. The ``requests-oauthlib`` library allows Requests users to easily make OAuth authenticated requests::5152 >>> import request52 >>> import requests53 >>> from requests_oauthlib import OAuth15455 >>> url = 'https://api.twitter.com/1.1/account/verify_credentials.json'56 >>> auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',
47 unmodified lines
modified:docs/api.rst+11 added-14 removed
46 unmodified lines
4748Exceptions49~~~~~~~~~~5051.. module:: requests51.. autoexception:: requests.exceptions.RequestException52.. autoexception:: requests.exceptions.ConnectionError53.. autoexception:: requests.exceptions.HTTPError54.. autoexception:: requests.exceptions.URLRequired55.. autoexception:: requests.exceptions.TooManyRedirects5653.. autoexception:: RequestException54.. autoexception:: ConnectionError55.. autoexception:: HTTPError56.. autoexception:: URLRequired57.. autoexception:: TooManyRedirects575958Status Code Lookup59~~~~~~~~~~~~~~~~~~6061.. autofunction:: requests.codes
11 unmodified lines
7374Cookies75~~~~~~~7679.. 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_cookiejar808182Encodings83~~~~~~~~~8487.. 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_response888990Classes91~~~~~~~
103 unmodified lines
modified:requests/__init__.py+6 added
46 unmodified lines
47__author__ = 'Kenneth Reitz'48__license__ = 'Apache 2.0'49__copyright__ = 'Copyright 2013 Kenneth Reitz'5051# Attempt to enable urllib3's SNI support, if possible52try:53 from requests.packages.urllib3.contrib import pyopenssl54 pyopenssl.inject_into_urllib3()55except ImportError:56 pass5758from . import utils59from .models import Request, Response, PreparedRequest60from .api import request, get, head, post, patch, put, delete, options
17 unmodified lines
modified:requests/models.py+16 added-8 removed
16 unmodified lines
1718from .auth import HTTPBasicAuth19from .cookies import cookiejar_from_dict, get_cookie_header20from .packages.urllib3.filepost import encode_multipart_formdata21from .packages.urllib3.util import parse_url22from .exceptions import HTTPError, RequestException, MissingSchema, InvalidURL23from .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 lines
284 except UnicodeDecodeError:285 pass286287 # 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)289290 if not scheme:291 raise MissingSchema("Invalid URL %r: No schema supplied" % url)292292 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)295296 # 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.')301302 # Carefully reconstruct the network location303 netloc = auth or ''304 if netloc:305 netloc += '@'306 netloc += host307 if port:308 netloc += ':' + str(port)309310 # Bare domains aren't valid URLs.311 if not path:312 path = '/'313
3 unmodified lines
317 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 lines
329 query = '%s&%s' % (query, enc_params)330 else:331 query = enc_params332325 url = requote_uri(urlunparse([scheme, netloc, path, _params, query, fragment]))333 url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))334 self.url = url335336 def prepare_headers(self, headers):337 """Prepares the given HTTP headers."""
315 unmodified lines
653 @property654 def links(self):655 """Returns the parsed header links of the response, if any."""656649 header = self.headers['link']657 header = self.headers.get('link')658659 # l = MultiDict()660 l = {}661
25 unmodified lines
modified:requests/sessions.py+9 added-5 removed
9 unmodified lines
10"""11import os12from datetime import datetime1314from .compat import cookielib14from .compat import cookielib, OrderedDict, urljoin, urlparse15from .cookies import cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar16from .models import Request, PreparedRequest17from .hooks import default_hooks, dispatch_hook18from .utils import from_key_val_list, default_headers19from .exceptions import TooManyRedirects, InvalidSchema2021from .compat import urlparse, urljoin21from .adapters import HTTPAdapter2223from .utils import requote_uri, get_environ_proxies, get_netrc_auth24
196 unmodified lines
221 # Set up a CookieJar to be used by default222 self.cookies = cookiejar_from_dict({})223224 # 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())228229 def __enter__(self):230 return self231
256 unmodified lines
488 for _, v in self.adapters.items():489 v.close()490491 def mount(self, prefix, adapter):493 """Registers a connection adapter to a prefix."""492 """Registers a connection adapter to a prefix.493494 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)499500 def __getstate__(self):501 return dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)502
9 unmodified lines
modified:requests/structures.py+62 added-25 removed
7 unmodified lines
89"""1011import os12import collections13from itertools import islice141516class IteratorProxy(object):
16 unmodified lines
33 def read(self, n):34 return "".join(islice(self.i, None, n))353636class CaseInsensitiveDict(dict):37 """Case-insensitive Dictionary37class CaseInsensitiveDict(collections.MutableMapping):38 """39 A case-insensitive ``dict``-like object.4041 Implements all methods and operations of42 ``collections.MutableMapping`` as well as dict's ``copy``. Also43 provides ``lower_items``.4445 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:5051 cid = CaseInsensitiveDict()52 cid['Accept'] = 'application/json'53 cid['aCCEPT'] == 'application/json' # True54 list(cid) == ['Accept'] # True5556 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.5942 @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.6348 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)7071 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)7576 def __getitem__(self, key):77 return self._store[key.lower()][1]7879 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()]8160 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())8463 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)8768 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 )9596 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())103104 # Copy is required105 def copy(self):106 return CaseInsensitiveDict(self._store.values())107108 def __repr__(self):109 return '%s(%r)' % (self.__class__.__name__, dict(self.items()))110111112class LookupDict(dict):113 """Dictionary lookup object."""114115 def __init__(self, name=None):
13 unmodified lines
modified:requests/utils.py+3 added-2 removed
21 unmodified lines
22from . import certs23from .compat import parse_http_list as _parse_list_header24from .compat import quote, urlparse, bytes, str, OrderedDict, urlunparse25from .cookies import RequestsCookieJar, cookiejar_from_dict26from .structures import CaseInsensitiveDict2728_hush_pyflakes = (RequestsCookieJar,)2930NETRC_FILES = ('.netrc', '_netrc')
418 unmodified lines
449 '%s/%s' % (p_system, p_release)])450451452def default_headers():452 return {453 return CaseInsensitiveDict({454 'User-Agent': default_user_agent(),455 'Accept-Encoding': ', '.join(('gzip', 'deflate', 'compress')),456 'Accept': '*/*'456 }457 })458459460def parse_header_links(value):461 """Return a dict of parsed link headers proxies.
89 unmodified lines
modified:.gitignore+1 added
3 unmodified lines
4nosetests.xml5junit-report.xml6pylint.txt7toy.py8tox.ini9violations.pyflakes.txt10cover/11build/12docs/_build
11 unmodified lines
modified:AUTHORS.rst+4 added
122 unmodified lines
123- 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 lines
7172But, you really shouldn't do that.737475Documentation76-------------7778Documentation is available at http://docs.python-requests.org/.798081Contribute82----------8384#. 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 lines
modified:setup.py+2 added-3 removed
18 unmodified lines
19 '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]2627requires = []
23 unmodified lines
51 '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',5657 ),58)
modified:test_requests.py+216 added
9 unmodified lines
10import pickle1112import requests13from requests.auth import HTTPDigestAuth14from requests.adapters import HTTPAdapter15from requests.compat import str, cookielib16from requests.cookies import cookiejar_from_dict17from requests.structures import CaseInsensitiveDict1819try:20 import StringIO21except ImportError:
437 unmodified lines
459460 r = s.send(r.prepare())461 self.assertEqual(r.status_code, 200)462463 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 )485486 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)523524 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)532533534class TestCaseInsensitiveDict(unittest.TestCase):535536 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)541542 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)547548 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)553554 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'])559560 def test_len(self):561 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})562 cid['A'] = 'a'563 self.assertEqual(len(cid), 2)564565 def test_getitem(self):566 cid = CaseInsensitiveDict({'Spam': 'blueval'})567 self.assertEqual(cid['spam'], 'blueval')568 self.assertEqual(cid['SPAM'], 'blueval')569570 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'])580581 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)587588 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)596597 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')605606 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')616617 def test_update_retains_unchanged(self):618 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})619 cid.update({'foo': 'newfoo'})620 self.assertEquals(cid['bar'], 'bar')621622 def test_iter(self):623 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})624 keys = frozenset(['Spam', 'Eggs'])625 self.assertEqual(frozenset(iter(cid)), keys)626627 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'})634635 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 )645646 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)654655 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)664665 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)676677678if __name__ == '__main__':679 unittest.main()