Merge branch 'master' of github.com:kennethreitz/requests
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 a8972a5, bb4326c · Browse files · 16 files·+111 added−45 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+111 added−45 removed
- tests:+35 added−4 removed
- other:+76 added−41 removed
Provenance
- Commit
a5b8f8d- Tree
dff24d4- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
Kenneth Reitz <me@kennethreitz.org>- Parent 1
a8972a5- Parent 2
bb4326c
16 files changed+111 added−45 removed
modified:docs/user/advanced.rst+2 added-6 removed
299 unmodified lines300 release the connection back to the pool unless you consume all the data or call301 :meth:`Response.close <requests.Response.close>`. This can lead to302 inefficiency with connections. If you find yourself partially reading request303 bodies (or not reading them at all) while using ``stream=True``, you should304-consider using ``contextlib.closing`` (`documented here`_), like this::304+make the request within a ``with`` statement to ensure it's always closed::305 306- from contextlib import closing307-308- with closing(requests.get('http://httpbin.org/get', stream=True)) as r:306+ with requests.get('http://httpbin.org/get', stream=True) as r:307 # Do things with the response here.308 311-.. _`documented here`: http://docs.python.org/2/library/contextlib.html#contextlib.closing312-309 .. _keep-alive:310 311 Keep-Alive312 ----------676 unmodified linesmodified:requests/__init__.py+30 added-22 removed
38 unmodified lines39 :copyright: (c) 2017 by Kenneth Reitz.40 :license: Apache 2.0, see LICENSE for more details.41 """42 43-# Check urllib3 for compatibility.43 import urllib345-urllib3_version = urllib3.__version__.split('.')46-# Sometimes, urllib3 only reports its version as 16.1.47-if len(urllib3_version) == 2:48- urllib3_version.append('0')49-major, minor, patch = urllib3_version50-major, minor, patch = int(major), int(minor), int(patch)51-# urllib3 >= 1.21.1, < 1.2252-try:44+import chardet45+import warnings46+from .exceptions import RequestsDependencyWarning47+48+49+def check_compatibility(urllib3_version, chardet_version):50+ urllib3_version = urllib3_version.split('.')51+ assert urllib3_version != ['dev'] # Verify urllib3 isn't installed from git.52+53+ # Sometimes, urllib3 only reports its version as 16.1.54+ if len(urllib3_version) == 2:55+ urllib3_version.append('0')56+57+ # Check urllib3 for compatibility.58+ major, minor, patch = urllib3_version # noqa: F81159+ major, minor, patch = int(major), int(minor), int(patch)60+ # urllib3 >= 1.21.1, < 1.2261 assert major == 162 assert minor >= 2163 assert minor <= 2256-except AssertionError:57- raise RuntimeError('Requests dependency \'urllib3\' must be version >= 1.21.1, < 1.22!')64 59-60-# Check chardet for compatibility.61-import chardet62-major, minor, patch = chardet.__version__.split('.')[:3]63-major, minor, patch = int(major), int(minor), int(patch)64-# chardet >= 3.0.2, < 3.1.065+ # Check chardet for compatibility.66+ major, minor, patch = chardet_version.split('.')[:3]67+ major, minor, patch = int(major), int(minor), int(patch)68+ # chardet >= 3.0.2, < 3.1.065-try:69 assert major == 370 assert minor < 171 assert patch >= 269-except AssertionError:70- raise RuntimeError('Requests dependency \'chardet\' must be version >= 3.0.2, < 3.1.0!')72 73+74+# Check imported dependencies for compatibility.75+try:76+ check_compatibility(urllib3.__version__, chardet.__version__)77+except (AssertionError, ValueError):78+ warnings.warn("urllib3 ({0}) or chardet ({1}) doesn't match a supported "79+ "version!".format(urllib3.__version__, chardet.__version__),80+ RequestsDependencyWarning)81+82 # Attempt to enable urllib3's SNI support, if possible83 try:84 from urllib3.contrib import pyopenssl85 pyopenssl.inject_into_urllib3()86 except ImportError:87 pass88 79-import warnings80-89 # urllib3's DependencyWarnings should be silenced.90 from urllib3.exceptions import DependencyWarning91 warnings.simplefilter('ignore', DependencyWarning)92 29 unmodified linesmodified:requests/api.py+1 added-1 removed
71 unmodified lines72 return request('get', url, params=params, **kwargs)73 74 75 def options(url, **kwargs):76- r"""Sends a OPTIONS request.76+ r"""Sends an OPTIONS request.77 78 :param url: URL for the new :class:`Request` object.79 :param \*\*kwargs: Optional arguments that ``request`` takes.80 :return: :class:`Response <Response>` object72 unmodified linesmodified:requests/exceptions.py+5 added
113 unmodified lines114 115 class FileModeWarning(RequestsWarning, DeprecationWarning):116 """A file was opened in text mode, but Requests determined its binary length."""117 pass118+119+120+class RequestsDependencyWarning(RequestsWarning):121+ """An imported dependency doesn't match the expected version range."""122+ passmodified:requests/help.py+1 added-1 removed
21 unmodified lines22 import cryptography23 24 25 def _implementation():26- """Return a dict with the Python implementation and verison.26+ """Return a dict with the Python implementation and version.27 28 Provide both the name and the version of the Python implementation29 currently running. For example, on CPython 2.7.5 it will return30 {'name': 'CPython', 'version': '2.7.5'}.81 unmodified linesmodified:requests/models.py+6 added
632 unmodified lines633 #: The :class:`PreparedRequest <PreparedRequest>` object to which this634 #: is a response.635 self.request = None636 637+ def __enter__(self):638+ return self639+640+ def __exit__(self, *args):641+ self.close()642+643 def __getstate__(self):644 # Consume everything; accessing the content attribute makes645 # sure the content has been fully read.646 if not self._content_consumed:304 unmodified linesmodified:requests/sessions.py
modified:requests/utils.py+7 added-7 removed
610 unmodified lines611 Save previous value, yield, and then restore the previous value stored in612 the environment variable 'env_name'.613 614 If 'value' is None, do nothing"""615- if value is not None:615+ value_changed = value is not None616+ if value_changed:617 old_value = os.environ.get(env_name)618 os.environ[env_name] = value619 try:620 yield621 finally:621- if value is None:622- return623- if old_value is None:624- del os.environ[env_name]625- else:626- os.environ[env_name] = old_value622+ if value_changed:623+ if old_value is None:624+ del os.environ[env_name]625+ else:626+ os.environ[env_name] = old_value627 628 629 def should_bypass_proxies(url, no_proxy):630 """274 unmodified linesmodified:tests/test_lowlevel.py
modified:tests/test_requests.py+7 added-2 removed
1-#!/usr/bin/env python1 # -*- coding: utf-8 -*-2 3 """Tests for Requests."""4 1661 unmodified lines1666 it = r.iter_lines()1667 next(it)1668 assert len(list(it)) == 31669 1670+ def test_response_context_manager(self, httpbin):1671+ with requests.get(httpbin('stream/4'), stream=True) as response:1672+ assert isinstance(response, requests.Response)1673+1674+ assert response.raw.closed1675+1676 def test_unconsumed_session_response_closes_connection(self, httpbin):1677 s = requests.session()1678 1679 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:688 unmodified lines2368 )2369 )2370 def test_parameters_for_nonstandard_schemes(self, input, params, expected):2371 """2367- Setting paramters for nonstandard schemes is allowed if those schemes2372+ Setting parameters for nonstandard schemes is allowed if those schemes2373 begin with "http", and is forbidden otherwise.2374 """2375 r = requests.Request('GET', url=input, params=params)2376 p = r.prepare()1 unmodified linemodified:tests/test_utils.py+28 added-2 removed
1 # -*- coding: utf-8 -*-2 3 import os4+import copy5 from io import BytesIO6 7 import pytest8 from requests import compat8 unmodified lines17 parse_header_links, prepend_scheme_if_needed,18 requote_uri, select_proxy, should_bypass_proxies, super_len,19 to_key_val_list, to_native_string,20 unquote_header_value, unquote_unreserved,20- urldefragauth, add_dict_to_cookiejar)21+ urldefragauth, add_dict_to_cookiejar, set_environ)22 from requests._internal_utils import unicode_is_ascii23 24 from .compat import StringIO, cStringIO25 625 unmodified lines651 monkeypatch.setenv('no_proxy', '')652 monkeypatch.setenv('NO_PROXY', '')653 monkeypatch.setattr(winreg, 'OpenKey', OpenKey)654 monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)654- assert should_bypass_proxies(url, no_proxy=None) == expected655+656+657+@pytest.mark.parametrize(658+ 'env_name, value', (659+ ('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),660+ ('no_proxy', None),661+ ('a_new_key', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),662+ ('a_new_key', None),663+ ))664+def test_set_environ(env_name, value):665+ """Tests set_environ will set environ values and will restore the environ."""666+ environ_copy = copy.deepcopy(os.environ)667+ with set_environ(env_name, value):668+ assert os.environ.get(env_name) == value669+670+ assert os.environ == environ_copy671+672+673+def test_set_environ_raises_exception():674+ """Tests set_environ will raise exceptions in context when the675+ value parameter is None."""676+ with pytest.raises(Exception) as exception:677+ with set_environ('test1', None):678+ raise Exception('Expected exception')679+680+ assert 'Expected exception' in str(exception.value)modified:.gitignore+1 added
3 unmodified lines4 nosetests.xml5 junit-report.xml6 pylint.txt7 toy.py8+.cache/9 cover/10 build/11 docs/_build12 requests.egg-info/11 unmodified linesmodified:AUTHORS.rst+2 added
181 unmodified lines182 - David Fontenot (`@davidfontenot <https://github.com/davidfontenot>`_)183 - Shmuel Amar (`@shmuelamar <https://github.com/shmuelamar>`_)184 - Gary Wu (`@garywu <https://github.com/garywu>`_)185 - Ryan Pineo (`@ryanpineo <https://github.com/ryanpineo>`_)186+- Ed Morley (`@edmorley <https://github.com/edmorley>`_)187+- Matt Liu <liumatt@gmail.com> (`@mlcrazy <https://github.com/mlcrazy>`_)modified:HISTORY.rst+15 added-1 removed
1 unmodified line2 3 Release History4 ---------------5 6+dev7++++8+9+**Improvements**10+11+- ``Response`` is now a context manager, so can be used directly in a `with` statement12+ without first having to be wrapped by ``contextlib.closing()``.13+14+**Bugfixes**15+16+- Resolve installation failure if multiprocessing is not available17+- Resolve tests crash if multiprocessing is not able to determine the number of CPU cores18+- Resolve error swallowing in utils set_environ generator19+20+21 2.17.3 (2017-05-29)22 +++++++++++++++++++23 24 **Improvements**1456 unmodified lines1481 ++++++++++++++++++1482 1483 * Frustration1484 * Conception1470-modified:Makefile+1 added-1 removed
6 unmodified lines7 ci:8 py.test -n 8 --boxed --junitxml=report.xml9 10 test-readme:11- python setup.py check -r -s11+ @python setup.py check --restructuredtext --strict && ([ $$? -eq 0 ] && echo "README.rst and HISTORY.rst ok") || echo "Invalid markup in README.rst or HISTORY.rst!"12 13 flake8:14 flake8 --ignore=E501,F401,E128,E402,E731,F821 requests15 12 unmodified linesmodified:setup.py+5 added-2 removed
6 unmodified lines7 from codecs import open8 9 from setuptools import setup10 from setuptools.command.test import test as TestCommand11-from multiprocessing import cpu_count11 12 here = os.path.abspath(os.path.dirname(__file__))13 14 class PyTest(TestCommand):15 user_options = [('pytest-args=', 'a', "Arguments to pass into py.test")]16 17 def initialize_options(self):18 TestCommand.initialize_options(self)19+ try:20+ from multiprocessing import cpu_count20- self.pytest_args = ['-n', str(cpu_count()), '--boxed']21+ self.pytest_args = ['-n', str(cpu_count()), '--boxed']22+ except (ImportError, NotImplementedError):23+ self.pytest_args = ['-n', '1', '--boxed']24 25 def finalize_options(self):26 TestCommand.finalize_options(self)27 self.test_args = []74 unmodified lines