Merge pull request #2927 from Lukasa/release/2.9.0
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Prepare 2.9.0 release.
authored by Ian Cordasco · committed by Ian Cordasco · parents 3d33f30, 424fe26 · Browse files · 24 files·+251 added−94 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
24 files+251 added−94 removed
- other:+251 added−94 removed
Provenance
- Commit
046a0f2- Tree
fdbba33- Author
Ian Cordasco <sigmavirus24@users.noreply.github.com>- Committer
Ian Cordasco <sigmavirus24@users.noreply.github.com>- Parent 1
3d33f30- Parent 2
424fe26
24 files changed+251 added−94 removed
modified:requests/packages/urllib3/contrib/appengine.py+12 added-11 removed
1+from __future__ import absolute_import2 import logging3 import os4 import warnings5 54 unmodified lines60 if not urlfetch:61 raise AppEnginePlatformError(62 "URLFetch is not available in this environment.")63 63- if is_prod_appengine_v2():64+ if is_prod_appengine_mvms():65 raise AppEnginePlatformError(66 "Use normal urllib3.PoolManager instead of AppEngineManager"67 "on Managed VMs, as using URLFetch is not necessary in "68 "this environment.")39 unmodified lines108 except urlfetch.DeadlineExceededError as e:109 raise TimeoutError(self, e)110 111 except urlfetch.InvalidURLError as e:111- if 'too large' in e.message:112+ if 'too large' in str(e):113 raise AppEnginePlatformError(114 "URLFetch request too large, URLFetch only "115 "supports requests up to 10mb in size.", e)116 raise ProtocolError(e)117 118 except urlfetch.DownloadError as e:118- if 'Too many redirects' in e.message:119+ if 'Too many redirects' in str(e):120 raise MaxRetryError(self, url, reason=e)121 raise ProtocolError(e)122 123 except urlfetch.ResponseTooLargeError as e:31 unmodified lines155 return http_response156 157 def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw):158 158- if is_prod_appengine_v1():159+ if is_prod_appengine():160 # Production GAE handles deflate encoding automatically, but does161 # not remove the encoding header.162 content_encoding = urlfetch_resp.headers.get('content-encoding')163 12 unmodified lines176 def _get_absolute_timeout(self, timeout):177 if timeout is Timeout.DEFAULT_TIMEOUT:178 return 5 # 5s is the default timeout for URLFetch.179 if isinstance(timeout, Timeout):179- if not timeout.read is timeout.connect:180+ if timeout.read is not timeout.connect:181 warnings.warn(182 "URLFetch does not support granular timeout settings, "183 "reverting to total timeout.", AppEnginePlatformWarning)184 return timeout.total14 unmodified lines199 200 201 def is_appengine():202 return (is_local_appengine() or202- is_prod_appengine_v1() or203- is_prod_appengine_v2())203+ is_prod_appengine() or204+ is_prod_appengine_mvms())205 206 207 def is_appengine_sandbox():207- return is_appengine() and not is_prod_appengine_v2()208+ return is_appengine() and not is_prod_appengine_mvms()209 210 211 def is_local_appengine():212 return ('APPENGINE_RUNTIME' in os.environ and213 'Development/' in os.environ['SERVER_SOFTWARE'])214 215 215-def is_prod_appengine_v1():216+def is_prod_appengine():217 return ('APPENGINE_RUNTIME' in os.environ and218 'Google App Engine/' in os.environ['SERVER_SOFTWARE'] and218- not is_prod_appengine_v2())219+ not is_prod_appengine_mvms())220 221 221-def is_prod_appengine_v2():222+def is_prod_appengine_mvms():223 return os.environ.get('GAE_VM', False) == 'true'modified:requests/packages/urllib3/contrib/ntlmpool.py+1 added
1 unmodified line2 NTLM authenticating pool, contributed by erikcederstran3 4 Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=105 """6+from __future__ import absolute_import7 8 try:9 from http.client import HTTPSConnection10 except ImportError:105 unmodified linesmodified:requests/packages/urllib3/contrib/pyopenssl.py+18 added-17 removed
41 unmodified lines42 .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication43 .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)44 45 '''46+from __future__ import absolute_import47 48 try:49 from ndg.httpsclient.ssl_peer_verification import SUBJ_ALT_NAME_SUPPORT50 from ndg.httpsclient.subj_alt_name import SubjectAltName as BaseSubjectAltName2 unmodified lines53 54 import OpenSSL.SSL55 from pyasn1.codec.der import decoder as der_decoder56 from pyasn1.type import univ, constraint56-from socket import _fileobject, timeout57+from socket import _fileobject, timeout, error as SocketError58 import ssl59 import select60 61 from .. import connection9 unmodified lines71 ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,72 ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,73 }74 75+if hasattr(ssl, 'PROTOCOL_TLSv1_1') and hasattr(OpenSSL.SSL, 'TLSv1_1_METHOD'):76+ _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD77+78+if hasattr(ssl, 'PROTOCOL_TLSv1_2') and hasattr(OpenSSL.SSL, 'TLSv1_2_METHOD'):79+ _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD80+81 try:82 _openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD})83 except AttributeError:84 pass85 86 _openssl_verify = {87 ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,88 ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,82- ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER83- + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,89+ ssl.CERT_REQUIRED:90+ OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,91 }92 93 DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS94 95 # OpenSSL will only write 16K at a time96 SSL_WRITE_BLOCKSIZE = 1638497 91-try:92- _ = memoryview93- has_memoryview = True94-except NameError:95- has_memoryview = False96-98 orig_util_HAS_SNI = util.HAS_SNI99 orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket100 101 10 unmodified lines112 connection.ssl_wrap_socket = orig_connection_ssl_wrap_socket113 util.HAS_SNI = orig_util_HAS_SNI114 115 115-### Note: This is a slightly bug-fixed version of same from ndg-httpsclient.116+# Note: This is a slightly bug-fixed version of same from ndg-httpsclient.117 class SubjectAltName(BaseSubjectAltName):118 '''ASN.1 implementation for subjectAltNames support'''119 120 # There is no limit to how many SAN certificates a certificate may have,2 unmodified lines123 sizeSpec = univ.SequenceOf.sizeSpec + \124 constraint.ValueSizeConstraint(1, 1024)125 126 126-### Note: This is a slightly bug-fixed version of same from ndg-httpsclient.127+# Note: This is a slightly bug-fixed version of same from ndg-httpsclient.128 def get_subj_alt_name(peer_cert):129 # Search through extensions130 dns_name = []131 if not SUBJ_ALT_NAME_SUPPORT:49 unmodified lines181 except OpenSSL.SSL.SysCallError as e:182 if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):183 return b''184 else:184- raise185+ raise SocketError(e)186 except OpenSSL.SSL.ZeroReturnError as e:187 if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:188 return b''189 else:22 unmodified lines212 raise timeout()213 continue214 215 def sendall(self, data):215- if has_memoryview and not isinstance(data, memoryview):216- data = memoryview(data)217-216 total_sent = 0217 while total_sent < len(data):220- sent = self._send_until_done(data[total_sent:total_sent+SSL_WRITE_BLOCKSIZE])218+ sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])219 total_sent += sent220 221 def shutdown(self):222 # FIXME rethrow compatible exceptions should we ever use this223 self.connection.shutdown()224 225 def close(self):226 if self._makefile_refs < 1:227+ try:229- return self.connection.close()228+ return self.connection.close()229+ except OpenSSL.SSL.Error:230+ return231 else:232 self._makefile_refs -= 1233 234 def getpeercert(self, binary_form=False):76 unmodified linesadded:requests/packages/urllib3/packages/ssl_match_hostname/.gitignore+1 added
1+envmodified:requests/packages/urllib3/packages/__init__.py+1 added
1 from __future__ import absolute_import2 3 from . import ssl_match_hostname4 5+__all__ = ('ssl_match_hostname', )modified:requests/packages/urllib3/util/__init__.py+20 added
1+from __future__ import absolute_import2 # For backwards compatibility, provide imports that used to be here.3 from .connection import is_connection_dropped4 from .request import make_headers5 from .response import is_fp_closed16 unmodified lines22 parse_url,23 split_first,24 Url,25 )26+27+__all__ = (28+ 'HAS_SNI',29+ 'SSLContext',30+ 'Retry',31+ 'Timeout',32+ 'Url',33+ 'assert_fingerprint',34+ 'current_time',35+ 'is_connection_dropped',36+ 'is_fp_closed',37+ 'get_host',38+ 'parse_url',39+ 'make_headers',40+ 'resolve_cert_reqs',41+ 'resolve_ssl_version',42+ 'split_first',43+ 'ssl_wrap_socket',44+)modified:requests/packages/urllib3/util/connection.py+1 added
1+from __future__ import absolute_import2 import socket3 try:4 from select import poll, POLLIN5 except ImportError: # `poll` doesn't exist on OSX and other platforms96 unmodified linesmodified:requests/packages/urllib3/util/request.py+1 added
1+from __future__ import absolute_import2 from base64 import b64encode3 4 from ..packages.six import b5 67 unmodified linesmodified:requests/packages/urllib3/util/response.py+2 added-1 removed
1+from __future__ import absolute_import2 from ..packages.six.moves import http_client as httplib3 4 from ..exceptions import HeaderParsingError5 38 unmodified lines44 45 # This will fail silently if we pass in the wrong kind of parameter.46 # To make debugging easier add an explicit check.47 if not isinstance(headers, httplib.HTTPMessage):47- raise TypeError('expected httplib.Message, got {}.'.format(48+ raise TypeError('expected httplib.Message, got {0}.'.format(49 type(headers)))50 51 defects = getattr(headers, 'defects', None)52 get_payload = getattr(headers, 'get_payload', None)22 unmodified linesmodified:requests/packages/urllib3/util/retry.py+4 added-3 removed
1+from __future__ import absolute_import2 import time3 import logging4 5 from ..exceptions import (120 unmodified lines126 self.status_forcelist = status_forcelist or set()127 self.method_whitelist = method_whitelist128 self.backoff_factor = backoff_factor129 self.raise_on_redirect = raise_on_redirect129- self._observed_errors = _observed_errors # TODO: use .history instead?130+ self._observed_errors = _observed_errors # TODO: use .history instead?131 132 def new(self, **kw):133 params = dict(134 total=self.total,71 unmodified lines206 return False207 208 return min(retry_counts) < 0209 209- def increment(self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None):210+ def increment(self, method=None, url=None, response=None, error=None,211+ _pool=None, _stacktrace=None):212 """ Return a new Retry object with incremented retry counters.213 214 :param response: A response object, or None, if the server did not215 return a response.59 unmodified lines275 log.debug("Incremented Retry for (url='%s'): %r" % (url, new_retry))276 277 return new_retry278 277-279 def __repr__(self):280 return ('{cls.__name__}(total={self.total}, connect={self.connect}, '281 'read={self.read}, redirect={self.redirect})').format(282 cls=type(self), self=self)4 unmodified linesmodified:requests/packages/urllib3/util/ssl_.py+35 added-4 removed
1+from __future__ import absolute_import2+import errno3+import warnings4+import hmac5+6 from binascii import hexlify, unhexlify7 from hashlib import md5, sha1, sha2568 4-from ..exceptions import SSLError, InsecurePlatformWarning9+from ..exceptions import SSLError, InsecurePlatformWarning, SNIMissingWarning10 11 12 SSLContext = None13 HAS_SNI = False5 unmodified lines19 40: sha1,20 64: sha256,21 }22 18-import errno19-import warnings23 24+def _const_compare_digest_backport(a, b):25+ """26+ Compare two digests of equal length in constant time.27+28+ The digests must be of type str/bytes.29+ Returns True if the digests match, and False otherwise.30+ """31+ result = abs(len(a) - len(b))32+ for l, r in zip(bytearray(a), bytearray(b)):33+ result |= l ^ r34+ return result == 035+36+37+_const_compare_digest = getattr(hmac, 'compare_digest',38+ _const_compare_digest_backport)39+40+41 try: # Test for SSL features42 import ssl43 from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv2344 from ssl import HAS_SNI # Has SNI?108 unmodified lines153 fingerprint_bytes = unhexlify(fingerprint.encode())154 155 cert_digest = hashfunc(cert).digest()156 137- if cert_digest != fingerprint_bytes:157+ if not _const_compare_digest(cert_digest, fingerprint_bytes):158 raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'159 .format(fingerprint, hexlify(cert_digest)))160 161 140 unmodified lines302 if certfile:303 context.load_cert_chain(certfile, keyfile)304 if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI305 return context.wrap_socket(sock, server_hostname=server_hostname)306+307+ warnings.warn(308+ 'An HTTPS request has been made, but the SNI (Subject Name '309+ 'Indication) extension to TLS is not available on this platform. '310+ 'This may cause the server to present an incorrect TLS '311+ 'certificate, which can cause validation failures. For more '312+ 'information, see '313+ 'https://urllib3.readthedocs.org/en/latest/security.html'314+ '#snimissingwarning.',315+ SNIMissingWarning316+ )317 return context.wrap_socket(sock)modified:requests/packages/urllib3/util/timeout.py+5 added-3 removed
1+from __future__ import absolute_import2 # The default socket timeout, used by httplib to indicate that no timeout was3 # specified by the user4 from socket import _GLOBAL_DEFAULT_TIMEOUT5 import time3 unmodified lines9 # A sentinel value to indicate that no timeout was specified by the user in10 # urllib311 _Default = object()12 13+14 def current_time():15 """16 Retrieve the current time. This function is mocked out in unit testing.17 """209 unmodified lines227 :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`228 has not yet been called on this object.229 """230 if (self.total is not None and229- self.total is not self.DEFAULT_TIMEOUT and230- self._read is not None and231- self._read is not self.DEFAULT_TIMEOUT):231+ self.total is not self.DEFAULT_TIMEOUT and232+ self._read is not None and233+ self._read is not self.DEFAULT_TIMEOUT):234 # In case the connect timeout has not yet been established.235 if self._start_connect is None:236 return self._read237 return max(0, min(self.total - self.get_connect_duration(),5 unmodified linesmodified:requests/packages/urllib3/util/url.py+4 added-1 removed
1+from __future__ import absolute_import2 from collections import namedtuple3 4 from ..exceptions import LocationParseError5 79 unmodified lines85 86 def __str__(self):87 return self.url88 89+90 def split_first(s, delims):91 """92 Given a string and an iterable of delimiters, split on the first found93 delimiter. Return two split parts and the matched delimiter.22 unmodified lines116 117 if min_idx is None or min_idx < 0:118 return s, '', None119 118- return s[:min_idx], s[min_idx+1:], min_delim120+ return s[:min_idx], s[min_idx + 1:], min_delim121 122 123 def parse_url(url):124 """82 unmodified lines207 path, query = path.split('?', 1)208 209 return Url(scheme, auth, host, port, path, query, fragment)210 211+212 def get_host(url):213 """214 Deprecated. Use :func:`.parse_url` instead.215 """2 unmodified linesmodified:requests/packages/urllib3/__init__.py+27 added-5 removed
1 """2 urllib3 - Thread-safe connection pooling and re-using.3 """4 5-__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'6-__license__ = 'MIT'7-__version__ = '1.12'5+from __future__ import absolute_import6+import warnings7 9-8 from .connectionpool import (9 HTTPConnectionPool,10 HTTPSConnectionPool,11 connection_from_url17 unmodified lines29 class NullHandler(logging.Handler):30 def emit(self, record):31 pass32 33+__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'34+__license__ = 'MIT'35+__version__ = '1.13'36+37+__all__ = (38+ 'HTTPConnectionPool',39+ 'HTTPSConnectionPool',40+ 'PoolManager',41+ 'ProxyManager',42+ 'HTTPResponse',43+ 'Retry',44+ 'Timeout',45+ 'add_stderr_logger',46+ 'connection_from_url',47+ 'disable_warnings',48+ 'encode_multipart_formdata',49+ 'get_host',50+ 'make_headers',51+ 'proxy_from_url',52+)53+54 logging.getLogger(__name__).addHandler(NullHandler())55 56+57 def add_stderr_logger(level=logging.DEBUG):58 """59 Helper for quickly adding a StreamHandler to the logger. Useful for60 debugging.13 unmodified lines74 # ... Clean up.75 del NullHandler76 77 58-import warnings78 # SecurityWarning's always go off by default.79 warnings.simplefilter('always', exceptions.SecurityWarning, append=True)80 # SubjectAltNameWarning's should go off once per host81 warnings.simplefilter('default', exceptions.SubjectAltNameWarning)82 # InsecurePlatformWarning's don't vary between requests, so we keep it default.83 warnings.simplefilter('default', exceptions.InsecurePlatformWarning,84 append=True)85+# SNIMissingWarnings should go off only once.86+warnings.simplefilter('default', exceptions.SNIMissingWarning)87 88+89 def disable_warnings(category=exceptions.HTTPWarning):90 """91 Helper for quickly disabling all urllib3 warnings.92 """1 unmodified linemodified:requests/packages/urllib3/_collections.py+4 added-3 removed
1+from __future__ import absolute_import2 from collections import Mapping, MutableMapping3 try:4 from threading import RLock5 except ImportError: # Platform-specific: No threads available161 unmodified lines167 168 def __ne__(self, other):169 return not self.__eq__(other)170 170- if not PY3: # Python 2171+ if not PY3: # Python 2172 iterkeys = MutableMapping.iterkeys173 itervalues = MutableMapping.itervalues174 175 __marker = object()58 unmodified lines234 with self.add instead of self.__setitem__235 """236 if len(args) > 1:237 raise TypeError("extend() takes at most 1 positional "237- "arguments ({} given)".format(len(args)))238+ "arguments ({0} given)".format(len(args)))239 other = args[0] if len(args) >= 1 else ()240 241 if isinstance(other, HTTPHeaderDict):242 for key, val in other.iteritems():61 unmodified lines304 def items(self):305 return list(self.iteritems())306 307 @classmethod307- def from_httplib(cls, message): # Python 2308+ def from_httplib(cls, message): # Python 2309 """Read headers from a Python 2 httplib message object."""310 # python2.7 does not expose a proper API for exporting multiheaders311 # efficiently. This function re-reads raw lines from the message312 # object and extracts the multiheaders properly.12 unmodified linesmodified:requests/packages/urllib3/connection.py+15 added-13 removed
1+from __future__ import absolute_import2 import datetime3+import os4 import sys5 import socket6 from socket import error as SocketError, timeout as SocketTimeout7 import warnings8 from .packages import six9 10 try: # Python 39- from http.client import HTTPConnection as _HTTPConnection, HTTPException11+ from http.client import HTTPConnection as _HTTPConnection12+ from http.client import HTTPException # noqa: unused in this module13 except ImportError:11- from httplib import HTTPConnection as _HTTPConnection, HTTPException14+ from httplib import HTTPConnection as _HTTPConnection15+ from httplib import HTTPException # noqa: unused in this module16 13-14-class DummyConnection(object):15- "Used to detect a failed ConnectionCls import."16- pass17-18-17 try: # Compiled with SSL?20- HTTPSConnection = DummyConnection18 import ssl19 BaseSSLError = ssl.SSLError20 except (ImportError, AttributeError): # Platform-specific: No SSL.21 ssl = None35 unmodified lines57 58 RECENT_DATE = datetime.date(2014, 1, 1)59 60 61+class DummyConnection(object):62+ """Used to detect a failed ConnectionCls import."""63+ pass64+65+66 class HTTPConnection(_HTTPConnection, object):67 """68 Based on httplib.HTTPConnection but provides an extra constructor69 backwards-compatibility layer between older and newer Pythons.136 unmodified lines206 207 self.key_file = key_file208 self.cert_file = cert_file209 self.cert_reqs = cert_reqs208- self.ca_certs = ca_certs209- self.ca_cert_dir = ca_cert_dir210 self.assert_hostname = assert_hostname211 self.assert_fingerprint = assert_fingerprint212+ self.ca_certs = ca_certs and os.path.expanduser(ca_certs)213+ self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)214 215 def connect(self):216 # Add certificate verification217 conn = self._new_conn()48 unmodified lines266 SubjectAltNameWarning267 )268 match_hostname(cert, self.assert_hostname or hostname)269 268- self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED269- or self.assert_fingerprint is not None)270+ self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED or271+ self.assert_fingerprint is not None)272 273 274 if ssl:275 # Make a copy for testing.4 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+18 added-16 removed
1+from __future__ import absolute_import2 import errno3 import logging4 import sys5 import warnings4 unmodified lines10 try: # Python 311 from queue import LifoQueue, Empty, Full12 except ImportError:13 from Queue import LifoQueue, Empty, Full13- import Queue as _ # Platform-specific: Windows14+ # Queue is imported for side effects on MS Windows15+ import Queue as _unused_module_Queue # noqa: unused16 17 18 from .exceptions import (19 ClosedPoolError,3 unmodified lines23 HostChangedError,24 LocationValueError,25 MaxRetryError,26 ProxyError,25- ConnectTimeoutError,27 ReadTimeoutError,28 SSLError,29 TimeoutError,30 InsecureRequestWarning,4 unmodified lines35 from .connection import (36 port_by_scheme,37 DummyConnection,38 HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,38- HTTPException, BaseSSLError, ConnectionError39+ HTTPException, BaseSSLError,40 )41 from .request import RequestMethods42 from .response import HTTPResponse43 10 unmodified lines54 55 _Default = object()56 57 57-## Pool objects58+# Pool objects59 class ConnectionPool(object):60 """61 Base class for all connection pools, such as62 :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.5 unmodified lines68 def __init__(self, host, port=None):69 if not host:70 raise LocationValueError("No host specified.")71 71- # httplib doesn't like it when we include brackets in ipv6 addresses72- self.host = host.strip('[]')72+ self.host = host73 self.port = port74 75 def __str__(self):76 return '%s(host=%r, port=%r)' % (type(self).__name__,567 unmodified lines644 raise645 return response646 647 log.info("Redirecting %s -> %s" % (url, redirect_location))648+ return self.urlopen(648- return self.urlopen(method, redirect_location, body, headers,649- retries=retries, redirect=redirect,650- assert_same_host=assert_same_host,651- timeout=timeout, pool_timeout=pool_timeout,652- release_conn=release_conn, **response_kw)649+ method, redirect_location, body, headers,650+ retries=retries, redirect=redirect,651+ assert_same_host=assert_same_host,652+ timeout=timeout, pool_timeout=pool_timeout,653+ release_conn=release_conn, **response_kw)654 655 # Check if we should retry the HTTP response.656 if retries.is_forced_retry(method, status_code=response.status):657 retries = retries.increment(method, url, response=response, _pool=self)658 retries.sleep()659 log.info("Forced retry: %s" % url)660+ return self.urlopen(659- return self.urlopen(method, url, body, headers,660- retries=retries, redirect=redirect,661- assert_same_host=assert_same_host,662- timeout=timeout, pool_timeout=pool_timeout,663- release_conn=release_conn, **response_kw)661+ method, url, body, headers,662+ retries=retries, redirect=redirect,663+ assert_same_host=assert_same_host,664+ timeout=timeout, pool_timeout=pool_timeout,665+ release_conn=release_conn, **response_kw)666 667 return response668 669 149 unmodified linesmodified:requests/packages/urllib3/exceptions.py+11 added-3 removed
1+from __future__ import absolute_import2+# Base Exceptions3 2-## Base Exceptions4 5 class HTTPError(Exception):6 "Base exception used by this module."7 pass8 9+10 class HTTPWarning(Warning):11 "Base warning used by this module."12 pass13 14 13-15 class PoolError(HTTPError):16 "Base exception for errors caused within a pool."17 def __init__(self, pool, message):18 self.pool = pool38 unmodified lines57 #: Renamed to ProtocolError but aliased for backwards compatibility.58 ConnectionError = ProtocolError59 60 60-## Leaf Exceptions61+# Leaf Exceptions62 63 class MaxRetryError(RequestError):64 """Raised when the maximum number of retries is exceeded.65 46 unmodified lines112 class ConnectTimeoutError(TimeoutError):113 "Raised when a socket timeout occurs while connecting to a server"114 pass115 116+117 class NewConnectionError(ConnectTimeoutError, PoolError):118 "Raised when we fail to establish a new connection. Usually ECONNREFUSED."119 pass120 121+122 class EmptyPoolError(PoolError):123 "Raised when a pool runs out of connections and no more are allowed."124 pass125 48 unmodified lines174 "Warned when certain SSL configuration is not available on a platform."175 pass176 177 178+class SNIMissingWarning(HTTPWarning):179+ "Warned when making a HTTPS request without SNI available."180+ pass181+182+183 class ResponseNotChunked(ProtocolError, ValueError):184 "Response needs to be chunked in order to read it as chunks."185 pass186 15 unmodified linesmodified:requests/packages/urllib3/fields.py+1 added
1+from __future__ import absolute_import2 import email.utils3 import mimetypes4 5 from .packages import six173 unmodified linesmodified:requests/packages/urllib3/filepost.py+1 added
1+from __future__ import absolute_import2 import codecs3 4 from uuid import uuid45 from io import BytesIO89 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+2 added-1 removed
1+from __future__ import absolute_import2 import logging3 4 try: # Python 35 from urllib.parse import urljoin19 unmodified lines25 26 log = logging.getLogger(__name__)27 28 SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',28- 'ssl_version')29+ 'ssl_version', 'ca_cert_dir')30 31 32 class PoolManager(RequestMethods):33 """248 unmodified linesmodified:requests/packages/urllib3/request.py+3 added-1 removed
1+from __future__ import absolute_import2 try:3 from urllib.parse import urlencode4 except ImportError:5 from urllib import urlencode127 unmodified lines133 extra_kw = {'headers': {}}134 135 if fields:136 if 'body' in urlopen_kw:136- raise TypeError('request got values for both \'fields\' and \'body\', can only specify one.')137+ raise TypeError(138+ "request got values for both 'fields' and 'body', can only specify one.")139 140 if encode_multipart:141 body, content_type = encode_multipart_formdata(fields, boundary=multipart_boundary)142 else:9 unmodified linesmodified:requests/packages/urllib3/response.py+41 added-12 removed
1+from __future__ import absolute_import2 from contextlib import contextmanager3 import zlib4 import io5 from socket import timeout as SocketTimeout6+from socket import error as SocketError7 8 from ._collections import HTTPHeaderDict9 from .exceptions import (10 ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked120 unmodified lines131 encodings = (enc.strip() for enc in tr_enc.split(","))132 if "chunked" in encodings:133 self.chunked = True134 133- # We certainly don't want to preload content when the response is chunked.134- if not self.chunked and preload_content and not self._body:135+ # If requested, preload the body.136+ if preload_content and not self._body:137 self._body = self.read(decode_content=decode_content)138 139 def get_redirect_location(self):140 """54 unmodified lines195 raise DecodeError(196 "Received response with content-encoding: %s, but "197 "failed to decode it." % content_encoding, e)198 197- if flush_decoder and decode_content and self._decoder:198- buf = self._decoder.decompress(binary_type())199- data += buf + self._decoder.flush()199+ if flush_decoder and decode_content:200+ data += self._flush_decoder()201 202 return data203 204+ def _flush_decoder(self):205+ """206+ Flushes the decoder. Should only be called if the decoder is actually207+ being used.208+ """209+ if self._decoder:210+ buf = self._decoder.decompress(b'')211+ return buf + self._decoder.flush()212+213+ return b''214+215 @contextmanager216 def _error_catcher(self):217 """218 Catch low-level python exceptions, instead re-raising urllib319 unmodified lines238 raise239 240 raise ReadTimeoutError(self._pool, None, 'Read timed out.')241 230- except HTTPException as e:242+ except (HTTPException, SocketError) as e:243 # This includes IncompleteRead.244 raise ProtocolError('Connection broken: %r' % e, e)245+246 except Exception:247 # The response may not be closed but we're not going to use it anymore248 # so close it now to ensure that the connection is released back to the pool.249 if self._original_response and not self._original_response.isclosed():250 self._original_response.close()251 252+ # Closing the response may not actually be sufficient to close253+ # everything, so if we have a hold of the connection close that254+ # too.255+ if self._connection is not None:256+ self._connection.close()257+258 raise259 finally:260 if self._original_response and self._original_response.isclosed():261 self.release_conn()57 unmodified lines319 self._body = data320 321 return data322 304-323 def stream(self, amt=2**16, decode_content=None):324 """325 A generator wrapper for the read() method. A call will block until326 ``amt`` bytes have been read from the connection or until the30 unmodified lines357 """358 headers = r.msg359 360 if not isinstance(headers, HTTPHeaderDict):343- if PY3: # Python 3361+ if PY3: # Python 3362 headers = HTTPHeaderDict(headers.items())345- else: # Python 2363+ else: # Python 2364 headers = HTTPHeaderDict.from_httplib(headers)365 366 # HTTPResponse objects in Python 3 don't have a .strict attribute367 strict = getattr(r, 'strict', 0)103 unmodified lines471 """472 self._init_decoder()473 # FIXME: Rewrite this method and make it a class with a better structured logic.474 if not self.chunked:457- raise ResponseNotChunked("Response is not chunked. "475+ raise ResponseNotChunked(476+ "Response is not chunked. "477 "Header 'transfer-encoding: chunked' is missing.")478 479 # Don't bother reading the body of a HEAD request.480 if self._original_response and is_response_to_head(self._original_response):5 unmodified lines486 self._update_chunk_length()487 if self.chunk_left == 0:488 break489 chunk = self._handle_chunk(amt)471- yield self._decode(chunk, decode_content=decode_content,472- flush_decoder=True)490+ decoded = self._decode(chunk, decode_content=decode_content,491+ flush_decoder=False)492+ if decoded:493+ yield decoded494 495+ if decode_content:496+ # On CPython and PyPy, we should never need to flush the497+ # decoder. However, on Jython we *might* need to, so498+ # lets defensively do it anyway.499+ decoded = self._flush_decoder()500+ if decoded: # Platform-specific: Jython.501+ yield decoded502+503 # Chunk content ends with \r\n: discard it.504 while True:505 line = self._fp.fp.readline()506 if not line:8 unmodified linesmodified:HISTORY.rst+23 added
8 unmodified lines9 **Minor Improvements** (Backwards compatible)10 11 - The ``verify`` keyword argument now supports being passed a path to a12 directory of CA certificates, not just a single-file bundle.13+- Warnings are now emitted when sending files opened in text mode.14+- Added the 511 Network Authentication Required status code to the status code15+ registry.16 17+**Bugfixes**18+19+- For file-like objects that are not seeked to the very beginning, we now20+ send the content length for the number of bytes we will actually read, rather21+ than the total size of the file, allowing partial file uploads.22+- When uploading file-like objects, if they are empty or have no obvious23+ content length we set ``Transfer-Encoding: chunked`` rather than24+ ``Content-Length: 0``.25+- We correctly receive the response in buffered mode when uploading chunked26+ bodies.27+- We now handle being passed a query string as a bytestring on Python 3, by28+ decoding it as UTF-8.29+- Sessions are now closed in all cases (exceptional and not) when using the30+ functional API rather than leaking and waiting for the garbage collector to31+ clean them up.32+- Correctly handle digest auth headers with a malformed ``qop`` directive that33+ contains no token, by treating it the same as if no ``qop`` directive was34+ provided at all.35+- Minor performance improvements when removing specific cookies by name.36+37 2.8.1 (2015-10-13)38 ++++++++++++++++++39 40 **Bugfixes**1073 unmodified lines