[Python-modules-commits] [requests] 02/13: Import requests_2.11.1.orig.tar.gz
Daniele Tricoli
eriol-guest at moszumanska.debian.org
Thu Sep 8 22:32:08 UTC 2016
This is an automated email from the git hooks/post-receive script.
eriol-guest pushed a commit to branch master
in repository requests.
commit 18d81e2cb9c8604a1f0b53fda23b035caa7601c9
Author: Daniele Tricoli <eriol at mornie.org>
Date: Thu Sep 8 22:00:13 2016 +0200
Import requests_2.11.1.orig.tar.gz
---
HISTORY.rst | 44 +-
PKG-INFO | 51 +-
README.rst | 5 +-
requests.egg-info/PKG-INFO | 51 +-
requests/__init__.py | 7 +-
requests/adapters.py | 22 +-
requests/api.py | 1 -
requests/auth.py | 12 +-
requests/certs.py | 4 +-
requests/compat.py | 6 +-
requests/cookies.py | 103 ++--
requests/exceptions.py | 18 +-
requests/hooks.py | 2 +-
requests/models.py | 54 ++-
requests/packages/urllib3/__init__.py | 2 +-
requests/packages/urllib3/connectionpool.py | 37 +-
requests/packages/urllib3/contrib/appengine.py | 2 +-
requests/packages/urllib3/contrib/socks.py | 2 +-
requests/packages/urllib3/packages/six.py | 635 ++++++++++++++++++++++---
requests/packages/urllib3/poolmanager.py | 93 +++-
requests/packages/urllib3/response.py | 4 +
requests/packages/urllib3/util/connection.py | 47 +-
requests/packages/urllib3/util/retry.py | 14 +-
requests/packages/urllib3/util/ssl_.py | 4 +-
requests/sessions.py | 71 ++-
requests/status_codes.py | 2 +-
requests/structures.py | 7 +-
requests/utils.py | 131 ++++-
requirements.txt | 1 +
29 files changed, 1193 insertions(+), 239 deletions(-)
diff --git a/HISTORY.rst b/HISTORY.rst
index 0eec48d..752bd2f 100644
--- a/HISTORY.rst
+++ b/HISTORY.rst
@@ -3,7 +3,47 @@
Release History
---------------
-2.10.0 (04-29-2016)
+2.11.1 (2016-08-17)
++++++++++++++++++++
+
+**Bugfixes**
+
+- Fixed a bug when using ``iter_content`` with ``decode_unicode=True`` for
+ streamed bodies would raise ``AttributeError``. This bug was introduced in
+ 2.11.
+- Strip Content-Type and Transfer-Encoding headers from the header block when
+ following a redirect that transforms the verb from POST/PUT to GET.
+
+2.11.0 (2016-08-08)
++++++++++++++++++++
+
+**Improvements**
+
+- Added support for the ``ALL_PROXY`` environment variable.
+- Reject header values that contain leading whitespace or newline characters to
+ reduce risk of header smuggling.
+
+**Bugfixes**
+
+- Fixed occasional ``TypeError`` when attempting to decode a JSON response that
+ occurred in an error case. Now correctly returns a ``ValueError``.
+- Requests would incorrectly ignore a non-CIDR IP address in the ``NO_PROXY``
+ environment variables: Requests now treats it as a specific IP.
+- Fixed a bug when sending JSON data that could cause us to encounter obscure
+ OpenSSL errors in certain network conditions (yes, really).
+- Added type checks to ensure that ``iter_content`` only accepts integers and
+ ``None`` for chunk sizes.
+- Fixed issue where responses whose body had not been fully consumed would have
+ the underlying connection closed but not returned to the connection pool,
+ which could cause Requests to hang in situations where the ``HTTPAdapter``
+ had been configured to use a blocking connection pool.
+
+**Miscellaneous**
+
+- Updated bundled urllib3 to 1.16.
+- Some previous releases accidentally accepted non-strings as acceptable header values. This release does not.
+
+2.10.0 (2016-04-29)
+++++++++++++++++++
**New Features**
@@ -14,7 +54,7 @@ Release History
- Updated bundled urllib3 to 1.15.1.
-2.9.2 (04-29-2016)
+2.9.2 (2016-04-29)
++++++++++++++++++
**Improvements**
diff --git a/PKG-INFO b/PKG-INFO
index 9fe4e72..f4d3003 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 1.1
Name: requests
-Version: 2.10.0
+Version: 2.11.1
Summary: Python HTTP for Humans.
Home-page: http://python-requests.org
Author: Kenneth Reitz
@@ -12,9 +12,6 @@ Description: Requests: HTTP for Humans
.. image:: https://img.shields.io/pypi/v/requests.svg
:target: https://pypi.python.org/pypi/requests
- .. image:: https://img.shields.io/pypi/dm/requests.svg
- :target: https://pypi.python.org/pypi/requests
-
Requests is the only *Non-GMO* HTTP library for Python, safe for human
consumption.
@@ -72,7 +69,7 @@ Description: Requests: HTTP for Humans
- Chunked Requests
- Thread-safety
- Requests supports Python 2.6 — 3.5, and runs great on PyPy.
+ Requests officially supports Python 2.6–2.7 & 3.3–3.5, and runs great on PyPy.
Installation
------------
@@ -110,7 +107,47 @@ Description: Requests: HTTP for Humans
Release History
---------------
- 2.10.0 (04-29-2016)
+ 2.11.1 (2016-08-17)
+ +++++++++++++++++++
+
+ **Bugfixes**
+
+ - Fixed a bug when using ``iter_content`` with ``decode_unicode=True`` for
+ streamed bodies would raise ``AttributeError``. This bug was introduced in
+ 2.11.
+ - Strip Content-Type and Transfer-Encoding headers from the header block when
+ following a redirect that transforms the verb from POST/PUT to GET.
+
+ 2.11.0 (2016-08-08)
+ +++++++++++++++++++
+
+ **Improvements**
+
+ - Added support for the ``ALL_PROXY`` environment variable.
+ - Reject header values that contain leading whitespace or newline characters to
+ reduce risk of header smuggling.
+
+ **Bugfixes**
+
+ - Fixed occasional ``TypeError`` when attempting to decode a JSON response that
+ occurred in an error case. Now correctly returns a ``ValueError``.
+ - Requests would incorrectly ignore a non-CIDR IP address in the ``NO_PROXY``
+ environment variables: Requests now treats it as a specific IP.
+ - Fixed a bug when sending JSON data that could cause us to encounter obscure
+ OpenSSL errors in certain network conditions (yes, really).
+ - Added type checks to ensure that ``iter_content`` only accepts integers and
+ ``None`` for chunk sizes.
+ - Fixed issue where responses whose body had not been fully consumed would have
+ the underlying connection closed but not returned to the connection pool,
+ which could cause Requests to hang in situations where the ``HTTPAdapter``
+ had been configured to use a blocking connection pool.
+
+ **Miscellaneous**
+
+ - Updated bundled urllib3 to 1.16.
+ - Some previous releases accidentally accepted non-strings as acceptable header values. This release does not.
+
+ 2.10.0 (2016-04-29)
+++++++++++++++++++
**New Features**
@@ -121,7 +158,7 @@ Description: Requests: HTTP for Humans
- Updated bundled urllib3 to 1.15.1.
- 2.9.2 (04-29-2016)
+ 2.9.2 (2016-04-29)
++++++++++++++++++
**Improvements**
diff --git a/README.rst b/README.rst
index 9fe548d..fbcb393 100644
--- a/README.rst
+++ b/README.rst
@@ -4,9 +4,6 @@ Requests: HTTP for Humans
.. image:: https://img.shields.io/pypi/v/requests.svg
:target: https://pypi.python.org/pypi/requests
-.. image:: https://img.shields.io/pypi/dm/requests.svg
- :target: https://pypi.python.org/pypi/requests
-
Requests is the only *Non-GMO* HTTP library for Python, safe for human
consumption.
@@ -64,7 +61,7 @@ Requests is ready for today's web.
- Chunked Requests
- Thread-safety
-Requests supports Python 2.6 — 3.5, and runs great on PyPy.
+Requests officially supports Python 2.6–2.7 & 3.3–3.5, and runs great on PyPy.
Installation
------------
diff --git a/requests.egg-info/PKG-INFO b/requests.egg-info/PKG-INFO
index 9fe4e72..f4d3003 100644
--- a/requests.egg-info/PKG-INFO
+++ b/requests.egg-info/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 1.1
Name: requests
-Version: 2.10.0
+Version: 2.11.1
Summary: Python HTTP for Humans.
Home-page: http://python-requests.org
Author: Kenneth Reitz
@@ -12,9 +12,6 @@ Description: Requests: HTTP for Humans
.. image:: https://img.shields.io/pypi/v/requests.svg
:target: https://pypi.python.org/pypi/requests
- .. image:: https://img.shields.io/pypi/dm/requests.svg
- :target: https://pypi.python.org/pypi/requests
-
Requests is the only *Non-GMO* HTTP library for Python, safe for human
consumption.
@@ -72,7 +69,7 @@ Description: Requests: HTTP for Humans
- Chunked Requests
- Thread-safety
- Requests supports Python 2.6 — 3.5, and runs great on PyPy.
+ Requests officially supports Python 2.6–2.7 & 3.3–3.5, and runs great on PyPy.
Installation
------------
@@ -110,7 +107,47 @@ Description: Requests: HTTP for Humans
Release History
---------------
- 2.10.0 (04-29-2016)
+ 2.11.1 (2016-08-17)
+ +++++++++++++++++++
+
+ **Bugfixes**
+
+ - Fixed a bug when using ``iter_content`` with ``decode_unicode=True`` for
+ streamed bodies would raise ``AttributeError``. This bug was introduced in
+ 2.11.
+ - Strip Content-Type and Transfer-Encoding headers from the header block when
+ following a redirect that transforms the verb from POST/PUT to GET.
+
+ 2.11.0 (2016-08-08)
+ +++++++++++++++++++
+
+ **Improvements**
+
+ - Added support for the ``ALL_PROXY`` environment variable.
+ - Reject header values that contain leading whitespace or newline characters to
+ reduce risk of header smuggling.
+
+ **Bugfixes**
+
+ - Fixed occasional ``TypeError`` when attempting to decode a JSON response that
+ occurred in an error case. Now correctly returns a ``ValueError``.
+ - Requests would incorrectly ignore a non-CIDR IP address in the ``NO_PROXY``
+ environment variables: Requests now treats it as a specific IP.
+ - Fixed a bug when sending JSON data that could cause us to encounter obscure
+ OpenSSL errors in certain network conditions (yes, really).
+ - Added type checks to ensure that ``iter_content`` only accepts integers and
+ ``None`` for chunk sizes.
+ - Fixed issue where responses whose body had not been fully consumed would have
+ the underlying connection closed but not returned to the connection pool,
+ which could cause Requests to hang in situations where the ``HTTPAdapter``
+ had been configured to use a blocking connection pool.
+
+ **Miscellaneous**
+
+ - Updated bundled urllib3 to 1.16.
+ - Some previous releases accidentally accepted non-strings as acceptable header values. This release does not.
+
+ 2.10.0 (2016-04-29)
+++++++++++++++++++
**New Features**
@@ -121,7 +158,7 @@ Description: Requests: HTTP for Humans
- Updated bundled urllib3 to 1.15.1.
- 2.9.2 (04-29-2016)
+ 2.9.2 (2016-04-29)
++++++++++++++++++
**Improvements**
diff --git a/requests/__init__.py b/requests/__init__.py
index 82c0f78..9c3b769 100644
--- a/requests/__init__.py
+++ b/requests/__init__.py
@@ -38,12 +38,11 @@ is at <http://python-requests.org>.
:copyright: (c) 2016 by Kenneth Reitz.
:license: Apache 2.0, see LICENSE for more details.
-
"""
__title__ = 'requests'
-__version__ = '2.10.0'
-__build__ = 0x021000
+__version__ = '2.11.1'
+__build__ = 0x021101
__author__ = 'Kenneth Reitz'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2016 Kenneth Reitz'
@@ -83,7 +82,5 @@ except ImportError:
logging.getLogger(__name__).addHandler(NullHandler())
-import warnings
-
# FileModeWarnings go off per the default.
warnings.simplefilter('default', FileModeWarning, append=True)
diff --git a/requests/adapters.py b/requests/adapters.py
index 23e448f..4a4c4e0 100644
--- a/requests/adapters.py
+++ b/requests/adapters.py
@@ -54,10 +54,24 @@ class BaseAdapter(object):
def __init__(self):
super(BaseAdapter, self).__init__()
- def send(self):
+ def send(self, request, stream=False, timeout=None, verify=True,
+ cert=None, proxies=None):
+ """Sends PreparedRequest object. Returns Response object.
+
+ :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
+ :param stream: (optional) Whether to stream the request content.
+ :param timeout: (optional) How long to wait for the server to send
+ data before giving up, as a float, or a :ref:`(connect timeout,
+ read timeout) <timeouts>` tuple.
+ :type timeout: float or tuple
+ :param verify: (optional) Whether to verify SSL certificates.
+ :param cert: (optional) Any user-provided SSL certificate to be trusted.
+ :param proxies: (optional) The proxies dictionary to apply to the request.
+ """
raise NotImplementedError
def close(self):
+ """Cleans up adapter specific items."""
raise NotImplementedError
@@ -154,6 +168,7 @@ class HTTPAdapter(BaseAdapter):
:param proxy: The proxy to return a urllib3 ProxyManager for.
:param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
:returns: ProxyManager
+ :rtype: requests.packages.urllib3.ProxyManager
"""
if proxy in self.proxy_manager:
manager = self.proxy_manager[proxy]
@@ -230,6 +245,7 @@ class HTTPAdapter(BaseAdapter):
:param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
:param resp: The urllib3 response object.
+ :rtype: requests.Response
"""
response = Response()
@@ -265,6 +281,7 @@ class HTTPAdapter(BaseAdapter):
:param url: The URL to connect to.
:param proxies: (optional) A Requests-style dictionary of proxies used on this request.
+ :rtype: requests.packages.urllib3.ConnectionPool
"""
proxy = select_proxy(url, proxies)
@@ -302,6 +319,7 @@ class HTTPAdapter(BaseAdapter):
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
+ :rtype: str
"""
proxy = select_proxy(request.url, proxies)
scheme = urlparse(request.url).scheme
@@ -343,6 +361,7 @@ class HTTPAdapter(BaseAdapter):
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxies: The url of the proxy being used for this request.
+ :rtype: dict
"""
headers = {}
username, password = get_auth_from_url(proxy)
@@ -365,6 +384,7 @@ class HTTPAdapter(BaseAdapter):
:param verify: (optional) Whether to verify SSL certificates.
:param cert: (optional) Any user-provided SSL certificate to be trusted.
:param proxies: (optional) The proxies dictionary to apply to the request.
+ :rtype: requests.Response
"""
conn = self.get_connection(request.url, proxies)
diff --git a/requests/api.py b/requests/api.py
index c2068d0..580b3f3 100644
--- a/requests/api.py
+++ b/requests/api.py
@@ -8,7 +8,6 @@ This module implements the Requests API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
-
"""
from . import sessions
diff --git a/requests/auth.py b/requests/auth.py
index 73f8e9d..49bcb24 100644
--- a/requests/auth.py
+++ b/requests/auth.py
@@ -43,6 +43,7 @@ class AuthBase(object):
class HTTPBasicAuth(AuthBase):
"""Attaches HTTP Basic Authentication to the given Request object."""
+
def __init__(self, username, password):
self.username = username
self.password = password
@@ -63,6 +64,7 @@ class HTTPBasicAuth(AuthBase):
class HTTPProxyAuth(HTTPBasicAuth):
"""Attaches HTTP Proxy Authentication to a given Request object."""
+
def __call__(self, r):
r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password)
return r
@@ -70,6 +72,7 @@ class HTTPProxyAuth(HTTPBasicAuth):
class HTTPDigestAuth(AuthBase):
"""Attaches HTTP Digest Authentication to the given Request object."""
+
def __init__(self, username, password):
self.username = username
self.password = password
@@ -87,6 +90,9 @@ class HTTPDigestAuth(AuthBase):
self._thread_local.num_401_calls = None
def build_digest_header(self, method, url):
+ """
+ :rtype: str
+ """
realm = self._thread_local.chal['realm']
nonce = self._thread_local.chal['nonce']
@@ -179,7 +185,11 @@ class HTTPDigestAuth(AuthBase):
self._thread_local.num_401_calls = 1
def handle_401(self, r, **kwargs):
- """Takes the given response and tries digest-auth, if needed."""
+ """
+ Takes the given response and tries digest-auth, if needed.
+
+ :rtype: requests.Response
+ """
if self._thread_local.pos is not None:
# Rewind the file position indicator of the body to where
diff --git a/requests/certs.py b/requests/certs.py
index 07e6475..f922b99 100644
--- a/requests/certs.py
+++ b/requests/certs.py
@@ -2,8 +2,8 @@
# -*- coding: utf-8 -*-
"""
-certs.py
-~~~~~~~~
+requests.certs
+~~~~~~~~~~~~~~
This module returns the preferred default CA certificate bundle.
diff --git a/requests/compat.py b/requests/compat.py
index 70edff7..eb6530d 100644
--- a/requests/compat.py
+++ b/requests/compat.py
@@ -1,7 +1,11 @@
# -*- coding: utf-8 -*-
"""
-pythoncompat
+requests.compat
+~~~~~~~~~~~~~~~
+
+This module handles import compatibility issues between Python 2 and
+Python 3.
"""
from .packages import chardet
diff --git a/requests/cookies.py b/requests/cookies.py
index eee5168..41a2fde 100644
--- a/requests/cookies.py
+++ b/requests/cookies.py
@@ -1,6 +1,9 @@
# -*- coding: utf-8 -*-
"""
+requests.cookies
+~~~~~~~~~~~~~~~~
+
Compatibility code to be able to use `cookielib.CookieJar` with requests.
requests.utils imports from here, so be careful with imports.
@@ -131,7 +134,11 @@ def extract_cookies_to_jar(jar, request, response):
def get_cookie_header(jar, request):
- """Produce an appropriate Cookie header string to be sent with `request`, or None."""
+ """
+ Produce an appropriate Cookie header string to be sent with `request`, or None.
+
+ :rtype: str
+ """
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie')
@@ -158,7 +165,8 @@ def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
class CookieConflictError(RuntimeError):
"""There are two cookies that meet the criteria specified in the cookie jar.
- Use .get and .set and include domain and path args in order to be more specific."""
+ Use .get and .set and include domain and path args in order to be more specific.
+ """
class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
@@ -178,12 +186,14 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
.. warning:: dictionary operations that are normally O(1) may be O(n).
"""
+
def get(self, name, default=None, domain=None, path=None):
"""Dict-like get() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
- .. warning:: operation is O(n), not O(1)."""
+ .. warning:: operation is O(n), not O(1).
+ """
try:
return self._find_no_duplicates(name, domain, path)
except KeyError:
@@ -192,7 +202,8 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
def set(self, name, value, **kwargs):
"""Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
- multiple domains."""
+ multiple domains.
+ """
# support client code that unsets cookies by assignment of a None value:
if value is None:
remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
@@ -207,37 +218,54 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
def iterkeys(self):
"""Dict-like iterkeys() that returns an iterator of names of cookies
- from the jar. See itervalues() and iteritems()."""
+ from the jar.
+
+ .. seealso:: itervalues() and iteritems().
+ """
for cookie in iter(self):
yield cookie.name
def keys(self):
"""Dict-like keys() that returns a list of names of cookies from the
- jar. See values() and items()."""
+ jar.
+
+ .. seealso:: values() and items().
+ """
return list(self.iterkeys())
def itervalues(self):
"""Dict-like itervalues() that returns an iterator of values of cookies
- from the jar. See iterkeys() and iteritems()."""
+ from the jar.
+
+ .. seealso:: iterkeys() and iteritems().
+ """
for cookie in iter(self):
yield cookie.value
def values(self):
"""Dict-like values() that returns a list of values of cookies from the
- jar. See keys() and items()."""
+ jar.
+
+ .. seealso:: keys() and items().
+ """
return list(self.itervalues())
def iteritems(self):
"""Dict-like iteritems() that returns an iterator of name-value tuples
- from the jar. See iterkeys() and itervalues()."""
+ from the jar.
+
+ .. seealso:: iterkeys() and itervalues().
+ """
for cookie in iter(self):
yield cookie.name, cookie.value
def items(self):
"""Dict-like items() that returns a list of name-value tuples from the
- jar. See keys() and values(). Allows client-code to call
- ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value
- pairs."""
+ jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
+ vanilla python dict of key value pairs.
+
+ .. seealso:: keys() and values().
+ """
return list(self.iteritems())
def list_domains(self):
@@ -258,7 +286,10 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
def multiple_domains(self):
"""Returns True if there are multiple domains in the jar.
- Returns False otherwise."""
+ Returns False otherwise.
+
+ :rtype: bool
+ """
domains = []
for cookie in iter(self):
if cookie.domain is not None and cookie.domain in domains:
@@ -269,7 +300,10 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
def get_dict(self, domain=None, path=None):
"""Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
- requirements."""
+ requirements.
+
+ :rtype: dict
+ """
dictionary = {}
for cookie in iter(self):
if (domain is None or cookie.domain == domain) and (path is None
@@ -288,20 +322,21 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead.
- .. warning:: operation is O(n), not O(1)."""
-
+ .. warning:: operation is O(n), not O(1).
+ """
return self._find_no_duplicates(name)
def __setitem__(self, name, value):
"""Dict-like __setitem__ for compatibility with client code. Throws
exception if there is already a cookie of that name in the jar. In that
- case, use the more explicit set() method instead."""
-
+ case, use the more explicit set() method instead.
+ """
self.set(name, value)
def __delitem__(self, name):
"""Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
- ``remove_cookie_by_name()``."""
+ ``remove_cookie_by_name()``.
+ """
remove_cookie_by_name(self, name)
def set_cookie(self, cookie, *args, **kwargs):
@@ -318,11 +353,17 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
super(RequestsCookieJar, self).update(other)
def _find(self, name, domain=None, path=None):
- """Requests uses this method internally to get cookie values. Takes as
- args name and optional domain and path. Returns a cookie.value. If
- there are conflicting cookies, _find arbitrarily chooses one. See
- _find_no_duplicates if you want an exception thrown if there are
- conflicting cookies."""
+ """Requests uses this method internally to get cookie values.
+
+ If there are conflicting cookies, _find arbitrarily chooses one.
+ See _find_no_duplicates if you want an exception thrown if there are
+ conflicting cookies.
+
+ :param name: a string containing name of cookie
+ :param domain: (optional) string containing domain of cookie
+ :param path: (optional) string containing path of cookie
+ :return: cookie.value
+ """
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
@@ -333,10 +374,16 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
def _find_no_duplicates(self, name, domain=None, path=None):
"""Both ``__get_item__`` and ``get`` call this function: it's never
- used elsewhere in Requests. Takes as args name and optional domain and
- path. Returns a cookie.value. Throws KeyError if cookie is not found
- and CookieConflictError if there are multiple cookies that match name
- and optionally domain and path."""
+ used elsewhere in Requests.
+
+ :param name: a string containing name of cookie
+ :param domain: (optional) string containing domain of cookie
+ :param path: (optional) string containing path of cookie
+ :raises KeyError: if cookie is not found
+ :raises CookieConflictError: if there are multiple cookies
+ that match name and optionally domain and path
+ :return: cookie.value
+ """
toReturn = None
for cookie in iter(self):
if cookie.name == name:
diff --git a/requests/exceptions.py b/requests/exceptions.py
index ba0b910..b89e0cc 100644
--- a/requests/exceptions.py
+++ b/requests/exceptions.py
@@ -5,19 +5,17 @@ requests.exceptions
~~~~~~~~~~~~~~~~~~~
This module contains the set of Requests' exceptions.
-
"""
from .packages.urllib3.exceptions import HTTPError as BaseHTTPError
class RequestException(IOError):
"""There was an ambiguous exception that occurred while handling your
- request."""
+ request.
+ """
def __init__(self, *args, **kwargs):
- """
- Initialize RequestException with `request` and `response` objects.
- """
+ """Initialize RequestException with `request` and `response` objects."""
response = kwargs.pop('response', None)
self.response = response
self.request = kwargs.pop('request', None)
@@ -80,7 +78,11 @@ class InvalidSchema(RequestException, ValueError):
class InvalidURL(RequestException, ValueError):
- """ The URL provided was somehow invalid. """
+ """The URL provided was somehow invalid."""
+
+
+class InvalidHeader(RequestException, ValueError):
+ """The header value provided was somehow invalid."""
class ChunkedEncodingError(RequestException):
@@ -108,7 +110,5 @@ class RequestsWarning(Warning):
class FileModeWarning(RequestsWarning, DeprecationWarning):
- """
- A file was opened in text mode, but Requests determined its binary length.
- """
+ """A file was opened in text mode, but Requests determined its binary length."""
pass
diff --git a/requests/hooks.py b/requests/hooks.py
index 9da9436..32b32de 100644
--- a/requests/hooks.py
+++ b/requests/hooks.py
@@ -10,10 +10,10 @@ Available hooks:
``response``:
The response generated from a Request.
-
"""
HOOKS = ['response']
+
def default_hooks():
return dict((event, []) for event in HOOKS)
diff --git a/requests/models.py b/requests/models.py
index fe4bec1..11434ef 100644
--- a/requests/models.py
+++ b/requests/models.py
@@ -27,7 +27,8 @@ from .exceptions import (
from .utils import (
guess_filename, get_auth_from_url, requote_uri,
stream_decode_response_unicode, to_key_val_list, parse_header_links,
- iter_slices, guess_json_utf, super_len, to_native_string)
+ iter_slices, guess_json_utf, super_len, to_native_string,
+ check_header_validity)
from .compat import (
cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,
is_py2, chardet, builtin_str, basestring)
@@ -37,11 +38,11 @@ from .status_codes import codes
#: The set of HTTP status codes that indicate an automatically
#: processable redirect.
REDIRECT_STATI = (
- codes.moved, # 301
- codes.found, # 302
- codes.other, # 303
- codes.temporary_redirect, # 307
- codes.permanent_redirect, # 308
+ codes.moved, # 301
+ codes.found, # 302
+ codes.other, # 303
+ codes.temporary_redirect, # 307
+ codes.permanent_redirect, # 308
)
DEFAULT_REDIRECT_LIMIT = 30
@@ -107,7 +108,6 @@ class RequestEncodingMixin(object):
if parameters are supplied as a dict.
The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
or 4-tuples (filename, fileobj, contentype, custom_headers).
-
"""
if (not files):
raise ValueError("Files must be provided.")
@@ -206,8 +206,8 @@ class Request(RequestHooksMixin):
>>> req = requests.Request('GET', 'http://httpbin.org/get')
>>> req.prepare()
<PreparedRequest [GET]>
-
"""
+
def __init__(self, method=None, url=None, headers=None, files=None,
data=None, params=None, auth=None, cookies=None, hooks=None, json=None):
@@ -269,7 +269,6 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
>>> s = requests.Session()
>>> s.send(r)
<Response [200]>
-
"""
def __init__(self):
@@ -403,10 +402,13 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
def prepare_headers(self, headers):
"""Prepares the given HTTP headers."""
+ self.headers = CaseInsensitiveDict()
if headers:
- self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items())
- else:
- self.headers = CaseInsensitiveDict()
+ for header in headers.items():
+ # Raise exception on invalid header value.
+ check_header_validity(header)
+ name, value = header
+ self.headers[to_native_string(name)] = value
def prepare_body(self, data, files, json=None):
"""Prepares the given HTTP body data."""
@@ -420,8 +422,12 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
length = None
if not data and json is not None:
+ # urllib3 requires a bytes-like body. Python 2's json.dumps
+ # provides this natively, but Python 3 gives a Unicode string.
content_type = 'application/json'
body = complexjson.dumps(json)
+ if not isinstance(body, bytes):
+ body = body.encode('utf-8')
is_stream = all([
hasattr(data, '__iter__'),
@@ -508,8 +514,8 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
can only be called once for the life of the
:class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls
to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
- header is removed beforehand."""
-
+ header is removed beforehand.
+ """
if isinstance(cookies, cookielib.CookieJar):
self._cookies = cookies
else:
@@ -653,6 +659,12 @@ class Response(object):
read into memory. This is not necessarily the length of each item
returned as decoding can take place.
+ chunk_size must be of type int or None. A value of None will
+ function differently depending on the value of `stream`.
+ stream=True will read data as it arrives in whatever size the
+ chunks are received. If stream=False, data is returned as
+ a single chunk.
+
If decode_unicode is True, content will be decoded using the best
available encoding based on the response.
"""
@@ -681,6 +693,8 @@ class Response(object):
if self._content_consumed and isinstance(self._content, bool):
raise StreamConsumedError()
+ elif chunk_size is not None and not isinstance(chunk_size, int):
+ raise TypeError("chunk_size must be an int, it is instead a %s." % type(chunk_size))
# simulate reading small chunks of the content
reused_chunks = iter_slices(self._content, chunk_size)
@@ -792,7 +806,7 @@ class Response(object):
:param \*\*kwargs: Optional arguments that ``json.loads`` takes.
"""
- if not self.encoding and len(self.content) > 3:
+ if not self.encoding and self.content and len(self.content) > 3:
# No encoding set. JSON RFC 4627 section 3 states we should expect
# UTF-8, -16 or -32. Detect which one to use; If the detection or
# decoding fails, fall back to `self.text` (using chardet to make
@@ -833,12 +847,16 @@ class Response(object):
"""Raises stored :class:`HTTPError`, if one occurred."""
http_error_msg = ''
+ if isinstance(self.reason, bytes):
+ reason = self.reason.decode('utf-8', 'ignore')
+ else:
+ reason = self.reason
if 400 <= self.status_code < 500:
- http_error_msg = '%s Client Error: %s for url: %s' % (self.status_code, self.reason, self.url)
+ http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url)
elif 500 <= self.status_code < 600:
- http_error_msg = '%s Server Error: %s for url: %s' % (self.status_code, self.reason, self.url)
+ http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url)
if http_error_msg:
raise HTTPError(http_error_msg, response=self)
@@ -850,6 +868,6 @@ class Response(object):
*Note: Should not normally need to be called explicitly.*
"""
if not self._content_consumed:
- return self.raw.close()
+ self.raw.close()
return self.raw.release_conn()
diff --git a/requests/packages/urllib3/__init__.py b/requests/packages/urllib3/__init__.py
index 7366899..c353674 100644
--- a/requests/packages/urllib3/__init__.py
+++ b/requests/packages/urllib3/__init__.py
@@ -32,7 +32,7 @@ except ImportError:
__author__ = 'Andrey Petrov (andrey.petrov at shazow.net)'
__license__ = 'MIT'
-__version__ = '1.15.1'
+__version__ = '1.16'
__all__ = (
'HTTPConnectionPool',
diff --git a/requests/packages/urllib3/connectionpool.py b/requests/packages/urllib3/connectionpool.py
index 3fcfb12..ab634cb 100644
--- a/requests/packages/urllib3/connectionpool.py
+++ b/requests/packages/urllib3/connectionpool.py
@@ -90,7 +90,7 @@ class ConnectionPool(object):
# Return False to re-raise any potential exceptions
return False
- def close():
+ def close(self):
"""
Close all pooled connections and disable the pool.
"""
@@ -163,6 +163,7 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
scheme = 'http'
ConnectionCls = HTTPConnection
+ ResponseCls = HTTPResponse
def __init__(self, host, port=None, strict=False,
timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False,
@@ -383,8 +384,13 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
try:
try: # Python 2.7, use buffering of HTTP responses
httplib_response = conn.getresponse(buffering=True)
- except TypeError: # Python 2.6 and older
- httplib_response = conn.getresponse()
+ except TypeError: # Python 2.6 and older, Python 3
+ try:
+ httplib_response = conn.getresponse()
+ except Exception as e:
+ # Remove the TypeError from the exception chain in Python 3;
+ # otherwise it looks like a programming error was the cause.
+ six.raise_from(e, None)
except (SocketTimeout, BaseSSLError, SocketError) as e:
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
raise
@@ -545,6 +551,17 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
conn = None
+ # Track whether `conn` needs to be released before
+ # returning/raising/recursing. Update this variable if necessary, and
+ # leave `release_conn` constant throughout the function. That way, if
+ # the function recurses, the original value of `release_conn` will be
... 1842 lines suppressed ...
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/requests.git
More information about the Python-modules-commits
mailing list