Skip to content
Myr

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

24 files+251 added−94 removed

modified:requests/packages/urllib3/contrib/appengine.py+12 added-11 removed
1from __future__ import absolute_import2import logging3import os4import warnings5
54 unmodified lines
60 if not urlfetch:61 raise AppEnginePlatformError(62 "URLFetch is not available in this environment.")6363 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 lines
108 except urlfetch.DeadlineExceededError as e:109 raise TimeoutError(self, e)110111 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)117118 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)122123 except urlfetch.ResponseTooLargeError as e:
31 unmodified lines
155 return http_response156157 def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw):158158 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 lines
176 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.total
14 unmodified lines
199200201def 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())205206207def is_appengine_sandbox():207 return is_appengine() and not is_prod_appengine_v2()208 return is_appengine() and not is_prod_appengine_mvms()209210211def is_local_appengine():212 return ('APPENGINE_RUNTIME' in os.environ and213 'Development/' in os.environ['SERVER_SOFTWARE'])214215215def is_prod_appengine_v1():216def 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())220221221def is_prod_appengine_v2():222def is_prod_appengine_mvms():223 return os.environ.get('GAE_VM', False) == 'true'
modified:requests/packages/urllib3/contrib/ntlmpool.py+1 added
1 unmodified line
2NTLM authenticating pool, contributed by erikcederstran34Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=105"""6from __future__ import absolute_import78try:9 from http.client import HTTPSConnection10except ImportError:
105 unmodified lines
modified:requests/packages/urllib3/contrib/pyopenssl.py+18 added-17 removed
41 unmodified lines
42.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication43.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)4445'''46from __future__ import absolute_import4748try:49 from ndg.httpsclient.ssl_peer_verification import SUBJ_ALT_NAME_SUPPORT50 from ndg.httpsclient.subj_alt_name import SubjectAltName as BaseSubjectAltName
2 unmodified lines
5354import OpenSSL.SSL55from pyasn1.codec.der import decoder as der_decoder56from pyasn1.type import univ, constraint56from socket import _fileobject, timeout57from socket import _fileobject, timeout, error as SocketError58import ssl59import select6061from .. import connection
9 unmodified lines
71 ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,72 ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,73}7475if hasattr(ssl, 'PROTOCOL_TLSv1_1') and hasattr(OpenSSL.SSL, 'TLSv1_1_METHOD'):76 _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD7778if hasattr(ssl, 'PROTOCOL_TLSv1_2') and hasattr(OpenSSL.SSL, 'TLSv1_2_METHOD'):79 _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD8081try:82 _openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD})83except AttributeError:84 pass8586_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}9293DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS9495# OpenSSL will only write 16K at a time96SSL_WRITE_BLOCKSIZE = 163849791try:92 _ = memoryview93 has_memoryview = True94except NameError:95 has_memoryview = False9698orig_util_HAS_SNI = util.HAS_SNI99orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket100101
10 unmodified lines
112 connection.ssl_wrap_socket = orig_connection_ssl_wrap_socket113 util.HAS_SNI = orig_util_HAS_SNI114115115### 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.117class SubjectAltName(BaseSubjectAltName):118 '''ASN.1 implementation for subjectAltNames support'''119120 # There is no limit to how many SAN certificates a certificate may have,
2 unmodified lines
123 sizeSpec = univ.SequenceOf.sizeSpec + \124 constraint.ValueSizeConstraint(1, 1024)125126126### 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.128def get_subj_alt_name(peer_cert):129 # Search through extensions130 dns_name = []131 if not SUBJ_ALT_NAME_SUPPORT:
49 unmodified lines
181 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 lines
212 raise timeout()213 continue214215 def sendall(self, data):215 if has_memoryview and not isinstance(data, memoryview):216 data = memoryview(data)217216 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 += sent220221 def shutdown(self):222 # FIXME rethrow compatible exceptions should we ever use this223 self.connection.shutdown()224225 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 -= 1233234 def getpeercert(self, binary_form=False):
76 unmodified lines
added:requests/packages/urllib3/packages/ssl_match_hostname/.gitignore+1 added
1env
modified:requests/packages/urllib3/packages/__init__.py+1 added
1from __future__ import absolute_import23from . import ssl_match_hostname45__all__ = ('ssl_match_hostname', )
modified:requests/packages/urllib3/util/__init__.py+20 added
1from __future__ import absolute_import2# For backwards compatibility, provide imports that used to be here.3from .connection import is_connection_dropped4from .request import make_headers5from .response import is_fp_closed
16 unmodified lines
22 parse_url,23 split_first,24 Url,25)2627__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
1from __future__ import absolute_import2import socket3try:4 from select import poll, POLLIN5except ImportError: # `poll` doesn't exist on OSX and other platforms
96 unmodified lines
modified:requests/packages/urllib3/util/request.py+1 added
1from __future__ import absolute_import2from base64 import b64encode34from ..packages.six import b5
67 unmodified lines
modified:requests/packages/urllib3/util/response.py+2 added-1 removed
1from __future__ import absolute_import2from ..packages.six.moves import http_client as httplib34from ..exceptions import HeaderParsingError5
38 unmodified lines
4445 # 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)))5051 defects = getattr(headers, 'defects', None)52 get_payload = getattr(headers, 'get_payload', None)
22 unmodified lines
modified:requests/packages/urllib3/util/retry.py+4 added-3 removed
1from __future__ import absolute_import2import time3import logging45from ..exceptions import (
120 unmodified lines
126 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?131132 def new(self, **kw):133 params = dict(134 total=self.total,
71 unmodified lines
206 return False207208 return min(retry_counts) < 0209209 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.213214 :param response: A response object, or None, if the server did not215 return a response.
59 unmodified lines
275 log.debug("Incremented Retry for (url='%s'): %r" % (url, new_retry))276277 return new_retry278277279 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 lines
modified:requests/packages/urllib3/util/ssl_.py+35 added-4 removed
1from __future__ import absolute_import2import errno3import warnings4import hmac56from binascii import hexlify, unhexlify7from hashlib import md5, sha1, sha25684from ..exceptions import SSLError, InsecurePlatformWarning9from ..exceptions import SSLError, InsecurePlatformWarning, SNIMissingWarning101112SSLContext = None13HAS_SNI = False
5 unmodified lines
19 40: sha1,20 64: sha256,21}2218import errno19import warnings2324def _const_compare_digest_backport(a, b):25 """26 Compare two digests of equal length in constant time.2728 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 == 0353637_const_compare_digest = getattr(hmac, 'compare_digest',38 _const_compare_digest_backport)394041try: # Test for SSL features42 import ssl43 from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv2344 from ssl import HAS_SNI # Has SNI?
108 unmodified lines
153 fingerprint_bytes = unhexlify(fingerprint.encode())154155 cert_digest = hashfunc(cert).digest()156137 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)))160161
140 unmodified lines
302 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)306307 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
1from __future__ import absolute_import2# The default socket timeout, used by httplib to indicate that no timeout was3# specified by the user4from socket import _GLOBAL_DEFAULT_TIMEOUT5import time
3 unmodified lines
9# A sentinel value to indicate that no timeout was specified by the user in10# urllib311_Default = object()121314def current_time():15 """16 Retrieve the current time. This function is mocked out in unit testing.17 """
209 unmodified lines
227 :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 lines
modified:requests/packages/urllib3/util/url.py+4 added-1 removed
1from __future__ import absolute_import2from collections import namedtuple34from ..exceptions import LocationParseError5
79 unmodified lines
8586 def __str__(self):87 return self.url888990def 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 lines
116117 if min_idx is None or min_idx < 0:118 return s, '', None119118 return s[:min_idx], s[min_idx+1:], min_delim120 return s[:min_idx], s[min_idx + 1:], min_delim121122123def parse_url(url):124 """
82 unmodified lines
207 path, query = path.split('?', 1)208209 return Url(scheme, auth, host, port, path, query, fragment)210211212def get_host(url):213 """214 Deprecated. Use :func:`.parse_url` instead.215 """
2 unmodified lines
modified:requests/packages/urllib3/__init__.py+27 added-5 removed
1"""2urllib3 - Thread-safe connection pooling and re-using.3"""45__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'6__license__ = 'MIT'7__version__ = '1.12'5from __future__ import absolute_import6import warnings798from .connectionpool import (9 HTTPConnectionPool,10 HTTPSConnectionPool,11 connection_from_url
17 unmodified lines
29 class NullHandler(logging.Handler):30 def emit(self, record):31 pass3233__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'34__license__ = 'MIT'35__version__ = '1.13'3637__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)5354logging.getLogger(__name__).addHandler(NullHandler())555657def add_stderr_logger(level=logging.DEBUG):58 """59 Helper for quickly adding a StreamHandler to the logger. Useful for60 debugging.
13 unmodified lines
74# ... Clean up.75del NullHandler767758import warnings78# SecurityWarning's always go off by default.79warnings.simplefilter('always', exceptions.SecurityWarning, append=True)80# SubjectAltNameWarning's should go off once per host81warnings.simplefilter('default', exceptions.SubjectAltNameWarning)82# InsecurePlatformWarning's don't vary between requests, so we keep it default.83warnings.simplefilter('default', exceptions.InsecurePlatformWarning,84 append=True)85# SNIMissingWarnings should go off only once.86warnings.simplefilter('default', exceptions.SNIMissingWarning)878889def disable_warnings(category=exceptions.HTTPWarning):90 """91 Helper for quickly disabling all urllib3 warnings.92 """
1 unmodified line
modified:requests/packages/urllib3/_collections.py+4 added-3 removed
1from __future__ import absolute_import2from collections import Mapping, MutableMapping3try:4 from threading import RLock5except ImportError: # Platform-specific: No threads available
161 unmodified lines
167168 def __ne__(self, other):169 return not self.__eq__(other)170170 if not PY3: # Python 2171 if not PY3: # Python 2172 iterkeys = MutableMapping.iterkeys173 itervalues = MutableMapping.itervalues174175 __marker = object()
58 unmodified lines
234 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 ()240241 if isinstance(other, HTTPHeaderDict):242 for key, val in other.iteritems():
61 unmodified lines
304 def items(self):305 return list(self.iteritems())306307 @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 lines
modified:requests/packages/urllib3/connection.py+15 added-13 removed
1from __future__ import absolute_import2import datetime3import os4import sys5import socket6from socket import error as SocketError, timeout as SocketTimeout7import warnings8from .packages import six910try: # 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 module13except ImportError:11 from httplib import HTTPConnection as _HTTPConnection, HTTPException14 from httplib import HTTPConnection as _HTTPConnection15 from httplib import HTTPException # noqa: unused in this module161314class DummyConnection(object):15 "Used to detect a failed ConnectionCls import."16 pass171817try: # Compiled with SSL?20 HTTPSConnection = DummyConnection18 import ssl19 BaseSSLError = ssl.SSLError20except (ImportError, AttributeError): # Platform-specific: No SSL.21 ssl = None
35 unmodified lines
5758RECENT_DATE = datetime.date(2014, 1, 1)596061class DummyConnection(object):62 """Used to detect a failed ConnectionCls import."""63 pass646566class HTTPConnection(_HTTPConnection, object):67 """68 Based on httplib.HTTPConnection but provides an extra constructor69 backwards-compatibility layer between older and newer Pythons.
136 unmodified lines
206207 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)214215 def connect(self):216 # Add certificate verification217 conn = self._new_conn()
48 unmodified lines
266 SubjectAltNameWarning267 )268 match_hostname(cert, self.assert_hostname or hostname)269268 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)272273274if ssl:275 # Make a copy for testing.
4 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+18 added-16 removed
1from __future__ import absolute_import2import errno3import logging4import sys5import warnings
4 unmodified lines
10try: # Python 311 from queue import LifoQueue, Empty, Full12except 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: unused161718from .exceptions import (19 ClosedPoolError,
3 unmodified lines
23 HostChangedError,24 LocationValueError,25 MaxRetryError,26 ProxyError,25 ConnectTimeoutError,27 ReadTimeoutError,28 SSLError,29 TimeoutError,30 InsecureRequestWarning,
4 unmodified lines
35from .connection import (36 port_by_scheme,37 DummyConnection,38 HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,38 HTTPException, BaseSSLError, ConnectionError39 HTTPException, BaseSSLError,40)41from .request import RequestMethods42from .response import HTTPResponse43
10 unmodified lines
5455_Default = object()565757## Pool objects58# Pool objects59class ConnectionPool(object):60 """61 Base class for all connection pools, such as62 :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.
5 unmodified lines
68 def __init__(self, host, port=None):69 if not host:70 raise LocationValueError("No host specified.")7171 # httplib doesn't like it when we include brackets in ipv6 addresses72 self.host = host.strip('[]')72 self.host = host73 self.port = port7475 def __str__(self):76 return '%s(host=%r, port=%r)' % (type(self).__name__,
567 unmodified lines
644 raise645 return response646647 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)654655 # 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)666667 return response668669
149 unmodified lines
modified:requests/packages/urllib3/exceptions.py+11 added-3 removed
1from __future__ import absolute_import2# Base Exceptions32## Base Exceptions45class HTTPError(Exception):6 "Base exception used by this module."7 pass8910class HTTPWarning(Warning):11 "Base warning used by this module."12 pass13141315class PoolError(HTTPError):16 "Base exception for errors caused within a pool."17 def __init__(self, pool, message):18 self.pool = pool
38 unmodified lines
57#: Renamed to ProtocolError but aliased for backwards compatibility.58ConnectionError = ProtocolError596060## Leaf Exceptions61# Leaf Exceptions6263class MaxRetryError(RequestError):64 """Raised when the maximum number of retries is exceeded.65
46 unmodified lines
112class ConnectTimeoutError(TimeoutError):113 "Raised when a socket timeout occurs while connecting to a server"114 pass115116117class NewConnectionError(ConnectTimeoutError, PoolError):118 "Raised when we fail to establish a new connection. Usually ECONNREFUSED."119 pass120121122class EmptyPoolError(PoolError):123 "Raised when a pool runs out of connections and no more are allowed."124 pass125
48 unmodified lines
174 "Warned when certain SSL configuration is not available on a platform."175 pass176177178class SNIMissingWarning(HTTPWarning):179 "Warned when making a HTTPS request without SNI available."180 pass181182183class ResponseNotChunked(ProtocolError, ValueError):184 "Response needs to be chunked in order to read it as chunks."185 pass186
15 unmodified lines
modified:requests/packages/urllib3/fields.py+1 added
1from __future__ import absolute_import2import email.utils3import mimetypes45from .packages import six
173 unmodified lines
modified:requests/packages/urllib3/filepost.py+1 added
1from __future__ import absolute_import2import codecs34from uuid import uuid45from io import BytesIO
89 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+2 added-1 removed
1from __future__ import absolute_import2import logging34try: # Python 35 from urllib.parse import urljoin
19 unmodified lines
2526log = logging.getLogger(__name__)2728SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',28 'ssl_version')29 'ssl_version', 'ca_cert_dir')303132class PoolManager(RequestMethods):33 """
248 unmodified lines
modified:requests/packages/urllib3/request.py+3 added-1 removed
1from __future__ import absolute_import2try:3 from urllib.parse import urlencode4except ImportError:5 from urllib import urlencode
127 unmodified lines
133 extra_kw = {'headers': {}}134135 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.")139140 if encode_multipart:141 body, content_type = encode_multipart_formdata(fields, boundary=multipart_boundary)142 else:
9 unmodified lines
modified:requests/packages/urllib3/response.py+41 added-12 removed
1from __future__ import absolute_import2from contextlib import contextmanager3import zlib4import io5from socket import timeout as SocketTimeout6from socket import error as SocketError78from ._collections import HTTPHeaderDict9from .exceptions import (10 ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked
120 unmodified lines
131 encodings = (enc.strip() for enc in tr_enc.split(","))132 if "chunked" in encodings:133 self.chunked = True134133 # 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)138139 def get_redirect_location(self):140 """
54 unmodified lines
195 raise DecodeError(196 "Received response with content-encoding: %s, but "197 "failed to decode it." % content_encoding, e)198197 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()201202 return data203204 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()212213 return b''214215 @contextmanager216 def _error_catcher(self):217 """218 Catch low-level python exceptions, instead re-raising urllib3
19 unmodified lines
238 raise239240 raise ReadTimeoutError(self._pool, None, 'Read timed out.')241230 except HTTPException as e:242 except (HTTPException, SocketError) as e:243 # This includes IncompleteRead.244 raise ProtocolError('Connection broken: %r' % e, e)245246 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()251252 # 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()257258 raise259 finally:260 if self._original_response and self._original_response.isclosed():261 self.release_conn()
57 unmodified lines
319 self._body = data320321 return data322304323 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 the
30 unmodified lines
357 """358 headers = r.msg359360 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)365366 # HTTPResponse objects in Python 3 don't have a .strict attribute367 strict = getattr(r, 'strict', 0)
103 unmodified lines
471 """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.")478479 # 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 lines
486 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 decoded494495 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 decoded502503 # Chunk content ends with \r\n: discard it.504 while True:505 line = self._fp.fp.readline()506 if not line:
8 unmodified lines
modified:HISTORY.rst+23 added
8 unmodified lines
9**Minor Improvements** (Backwards compatible)1011- 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.1617**Bugfixes**1819- 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.36372.8.1 (2015-10-13)38++++++++++++++++++3940**Bugfixes**
1073 unmodified lines