Skip to content
Myr

Upgrade urllib3 to 7fcfcd08a6a2150f93144d111904d1e4fb65c909

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Ian Cordasco · committed by Ian Cordasco · parent 77d7e53 · Browse files · 13 files+476 added−111 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

13 files+476 added−111 removed

  • other:+476 added−111 removed

13 files+476 added−111 removed

added:requests/packages/urllib3/contrib/appengine.py+222 added
1import logging2import os3import warnings45from ..exceptions import (6 HTTPError,7 HTTPWarning,8 MaxRetryError,9 ProtocolError,10 TimeoutError,11 SSLError12)1314from ..packages.six import BytesIO15from ..request import RequestMethods16from ..response import HTTPResponse17from ..util.timeout import Timeout18from ..util.retry import Retry1920try:21 from google.appengine.api import urlfetch22except ImportError:23 urlfetch = None242526log = logging.getLogger(__name__)272829class AppEnginePlatformWarning(HTTPWarning):30 pass313233class AppEnginePlatformError(HTTPError):34 pass353637class AppEngineManager(RequestMethods):38 """39 Connection manager for Google App Engine sandbox applications.4041 This manager uses the URLFetch service directly instead of using the42 emulated httplib, and is subject to URLFetch limitations as described in43 the App Engine documentation here:4445 https://cloud.google.com/appengine/docs/python/urlfetch4647 Notably it will raise an AppEnginePlatformError if:48 * URLFetch is not available.49 * If you attempt to use this on GAEv2 (Managed VMs), as full socket50 support is available.51 * If a request size is more than 10 megabytes.52 * If a response size is more than 32 megabtyes.53 * If you use an unsupported request method such as OPTIONS.5455 Beyond those cases, it will raise normal urllib3 errors.56 """5758 def __init__(self, headers=None, retries=None, validate_certificate=True):59 if not urlfetch:60 raise AppEnginePlatformError(61 "URLFetch is not available in this environment.")6263 if is_prod_appengine_v2():64 raise AppEnginePlatformError(65 "Use normal urllib3.PoolManager instead of AppEngineManager"66 "on Managed VMs, as using URLFetch is not necessary in "67 "this environment.")6869 warnings.warn(70 "urllib3 is using URLFetch on Google App Engine sandbox instead "71 "of sockets. To use sockets directly instead of URLFetch see "72 "https://urllib3.readthedocs.org/en/latest/contrib.html.",73 AppEnginePlatformWarning)7475 RequestMethods.__init__(self, headers)76 self.validate_certificate = validate_certificate7778 self.retries = retries or Retry.DEFAULT7980 def __enter__(self):81 return self8283 def __exit__(self, exc_type, exc_val, exc_tb):84 # Return False to re-raise any potential exceptions85 return False8687 def urlopen(self, method, url, body=None, headers=None,88 retries=None, redirect=True, timeout=Timeout.DEFAULT_TIMEOUT,89 **response_kw):9091 retries = self._get_retries(retries, redirect)9293 try:94 response = urlfetch.fetch(95 url,96 payload=body,97 method=method,98 headers=headers or {},99 allow_truncated=False,100 follow_redirects=(101 redirect and102 retries.redirect != 0 and103 retries.total),104 deadline=self._get_absolute_timeout(timeout),105 validate_certificate=self.validate_certificate,106 )107 except urlfetch.DeadlineExceededError as e:108 raise TimeoutError(self, e)109110 except urlfetch.InvalidURLError as e:111 if 'too large' in e.message:112 raise AppEnginePlatformError(113 "URLFetch request too large, URLFetch only "114 "supports requests up to 10mb in size.", e)115 raise ProtocolError(e)116117 except urlfetch.DownloadError as e:118 if 'Too many redirects' in e.message:119 raise MaxRetryError(self, url, reason=e)120 raise ProtocolError(e)121122 except urlfetch.ResponseTooLargeError as e:123 raise AppEnginePlatformError(124 "URLFetch response too large, URLFetch only supports"125 "responses up to 32mb in size.", e)126127 except urlfetch.SSLCertificateError as e:128 raise SSLError(e)129130 except urlfetch.InvalidMethodError as e:131 raise AppEnginePlatformError(132 "URLFetch does not support method: %s" % method, e)133134 http_response = self._urlfetch_response_to_http_response(135 response, **response_kw)136137 # Check for redirect response138 if (http_response.get_redirect_location() and139 retries.raise_on_redirect and redirect):140 raise MaxRetryError(self, url, "too many redirects")141142 # Check if we should retry the HTTP response.143 if retries.is_forced_retry(method, status_code=http_response.status):144 retries = retries.increment(145 method, url, response=http_response, _pool=self)146 log.info("Forced retry: %s" % url)147 retries.sleep()148 return self.urlopen(149 method, url,150 body=body, headers=headers,151 retries=retries, redirect=redirect,152 timeout=timeout, **response_kw)153154 return http_response155156 def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw):157158 if is_prod_appengine_v1():159 # Production GAE handles deflate encoding automatically, but does160 # not remove the encoding header.161 content_encoding = urlfetch_resp.headers.get('content-encoding')162163 if content_encoding == 'deflate':164 del urlfetch_resp.headers['content-encoding']165166 return HTTPResponse(167 # In order for decoding to work, we must present the content as168 # a file-like object.169 body=BytesIO(urlfetch_resp.content),170 headers=urlfetch_resp.headers,171 status=urlfetch_resp.status_code,172 **response_kw173 )174175 def _get_absolute_timeout(self, timeout):176 if timeout is Timeout.DEFAULT_TIMEOUT:177 return 5 # 5s is the default timeout for URLFetch.178 if isinstance(timeout, Timeout):179 if not timeout.read is timeout.connect:180 warnings.warn(181 "URLFetch does not support granular timeout settings, "182 "reverting to total timeout.", AppEnginePlatformWarning)183 return timeout.total184 return timeout185186 def _get_retries(self, retries, redirect):187 if not isinstance(retries, Retry):188 retries = Retry.from_int(189 retries, redirect=redirect, default=self.retries)190191 if retries.connect or retries.read or retries.redirect:192 warnings.warn(193 "URLFetch only supports total retries and does not "194 "recognize connect, read, or redirect retry parameters.",195 AppEnginePlatformWarning)196197 return retries198199200def is_appengine():201 return (is_local_appengine() or202 is_prod_appengine_v1() or203 is_prod_appengine_v2())204205206def is_appengine_sandbox():207 return is_appengine() and not is_prod_appengine_v2()208209210def is_local_appengine():211 return ('APPENGINE_RUNTIME' in os.environ and212 'Development/' in os.environ['SERVER_SOFTWARE'])213214215def is_prod_appengine_v1():216 return ('APPENGINE_RUNTIME' in os.environ and217 'Google App Engine/' in os.environ['SERVER_SOFTWARE'] and218 not is_prod_appengine_v2())219220221def is_prod_appengine_v2():222 return os.environ.get('GAE_VM', False) == 'true'
modified:requests/packages/urllib3/contrib/pyopenssl.py+21 added-5 removed
83 unmodified lines
84}8586DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS8788# OpenSSL will only write 16K at a time89SSL_WRITE_BLOCKSIZE = 163849091try:92 _ = memoryview93 has_memoryview = True94except NameError:95 has_memoryview = False9697orig_util_HAS_SNI = util.HAS_SNI98orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket99100
110 unmodified lines
211 raise timeout()212 continue213214 def sendall(self, data):207 while len(data):208 sent = self._send_until_done(data)209 data = data[sent:]215 if has_memoryview and not isinstance(data, memoryview):216 data = memoryview(data)217218 total_sent = 0219 while total_sent < len(data):220 sent = self._send_until_done(data[total_sent:total_sent+SSL_WRITE_BLOCKSIZE])221 total_sent += sent222223 def shutdown(self):224 # FIXME rethrow compatible exceptions should we ever use this225 self.connection.shutdown()226227 def close(self):228 if self._makefile_refs < 1:213 return self.connection.shutdown()229 return self.connection.close()230 else:231 self._makefile_refs -= 1232233 def getpeercert(self, binary_form=False):
68 unmodified lines
302 if not rd:303 raise timeout('select timed out')304 continue305 except OpenSSL.SSL.Error as e:290 raise ssl.SSLError('bad handshake', e)306 raise ssl.SSLError('bad handshake: %r' % e)307 break308309 return WrappedSocket(cnx, sock)
modified:requests/packages/urllib3/util/connection.py+2 added
58 unmodified lines
59 An host of '' or port 0 tells the OS to use the default.60 """6162 host, port = address63 if host.startswith('['):64 host = host.strip('[]')65 err = None66 for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):67 af, socktype, proto, canonname, sa = res68 sock = None
32 unmodified lines
modified:requests/packages/urllib3/util/response.py+54 added
1try:2 import http.client as httplib3except ImportError:4 import httplib56from ..exceptions import HeaderParsingError789def is_fp_closed(obj):10 """11 Checks whether a given file-like object is closed.12
14 unmodified lines
27 except AttributeError:28 pass2930 raise ValueError("Unable to determine whether fp is closed.")313233def assert_header_parsing(headers):34 """35 Asserts whether all headers have been successfully parsed.36 Extracts encountered errors from the result of parsing headers.3738 Only works on Python 3.3940 :param headers: Headers to verify.41 :type headers: `httplib.HTTPMessage`.4243 :raises urllib3.exceptions.HeaderParsingError:44 If parsing errors are found.45 """4647 # This will fail silently if we pass in the wrong kind of parameter.48 # To make debugging easier add an explicit check.49 if not isinstance(headers, httplib.HTTPMessage):50 raise TypeError('expected httplib.Message, got {}.'.format(51 type(headers)))5253 defects = getattr(headers, 'defects', None)54 get_payload = getattr(headers, 'get_payload', None)5556 unparsed_data = None57 if get_payload: # Platform-specific: Python 3.58 unparsed_data = get_payload()5960 if defects or unparsed_data:61 raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)626364def is_response_to_head(response):65 """66 Checks, wether a the request of a response has been a HEAD-request.67 Handles the quirks of AppEngine.6869 :param conn:70 :type conn: :class:`httplib.HTTPResponse`71 """72 # FIXME: Can we do this somehow without accessing private httplib _method?73 method = response._method74 if isinstance(method, int): # Platform-specific: Appengine75 return method == 376 return method.upper() == 'HEAD'
modified:requests/packages/urllib3/util/retry.py+1 added-1 removed
92 unmodified lines
93 {backoff factor} * (2 ^ ({number of total retries} - 1))9495 seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep96 for [0.1s, 0.2s, 0.4s, ...] between retries. It will never be longer97 than :attr:`Retry.MAX_BACKOFF`.97 than :attr:`Retry.BACKOFF_MAX`.9899 By default, backoff is disabled (set to 0).100101 :param bool raise_on_redirect: Whether, if the number of redirects is
184 unmodified lines
modified:requests/packages/urllib3/util/ssl_.py+14 added-17 removed
6 unmodified lines
7SSLContext = None8HAS_SNI = False9create_default_context = None1011# Maps the length of a digest to a possible hash function producing this digest12HASHFUNC_MAP = {13 32: md5,14 40: sha1,15 64: sha256,16}1718import errno19import warnings2021try: # Test for SSL features
96 unmodified lines
118 :param fingerprint:119 Fingerprint as string of hexdigits, can be interspersed by colons.120 """121115 # Maps the length of a digest to a possible hash function producing116 # this digest.117 hashfunc_map = {118 16: md5,119 20: sha1,120 32: sha256,121 }122122 fingerprint = fingerprint.replace(':', '').lower()124 digest_length, odd = divmod(len(fingerprint), 2)123 digest_length = len(fingerprint)124 hashfunc = HASHFUNC_MAP.get(digest_length)125 if not hashfunc:126 raise SSLError(127 'Fingerprint of invalid length: {0}'.format(fingerprint))128126 if odd or digest_length not in hashfunc_map:127 raise SSLError('Fingerprint is of invalid length.')128129 # We need encode() here for py32; works on py2 and p33.130 fingerprint_bytes = unhexlify(fingerprint.encode())131132 hashfunc = hashfunc_map[digest_length]133132 cert_digest = hashfunc(cert).digest()133136 if not cert_digest == fingerprint_bytes:134 if cert_digest != fingerprint_bytes:135 raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'138 .format(hexlify(fingerprint_bytes),139 hexlify(cert_digest)))136 .format(fingerprint, hexlify(cert_digest)))137138139def resolve_cert_reqs(candidate):140 """
137 unmodified lines
modified:requests/packages/urllib3/__init__.py+3 added-1 removed
2 unmodified lines
3"""45__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'6__license__ = 'MIT'7__version__ = '1.10.4'7__version__ = 'dev'8910from .connectionpool import (11 HTTPConnectionPool,
45 unmodified lines
5758import warnings59# SecurityWarning's always go off by default.60warnings.simplefilter('always', exceptions.SecurityWarning, append=True)61# SubjectAltNameWarning's should go off once per host62warnings.simplefilter('default', exceptions.SubjectAltNameWarning)63# InsecurePlatformWarning's don't vary between requests, so we keep it default.64warnings.simplefilter('default', exceptions.InsecurePlatformWarning,65 append=True)66
5 unmodified lines
modified:requests/packages/urllib3/connection.py+9 added-5 removed
36 unmodified lines
3738from .exceptions import (39 ConnectTimeoutError,40 SystemTimeWarning,41 SecurityWarning,41 SubjectAltNameWarning,42)43from .packages.ssl_match_hostname import match_hostname4445from .util.ssl_ import (
145 unmodified lines
191 def set_cert(self, key_file=None, cert_file=None,192 cert_reqs=None, ca_certs=None,193 assert_hostname=None, assert_fingerprint=None):194195 if ca_certs and cert_reqs is None:196 cert_reqs = 'CERT_REQUIRED'197198 self.key_file = key_file199 self.cert_file = cert_file200 self.cert_reqs = cert_reqs201 self.ca_certs = ca_certs
45 unmodified lines
247 and self.assert_hostname is not False:248 cert = self.sock.getpeercert()249 if not cert.get('subjectAltName', ()):250 warnings.warn((248 'Certificate has no `subjectAltName`, falling back to check for a `commonName` for now. '249 'This feature is being removed by major browsers and deprecated by RFC 2818. '250 '(See https://github.com/shazow/urllib3/issues/497 for details.)'),251 SecurityWarning251 'Certificate for {0} has no `subjectAltName`, falling back to check for a '252 '`commonName` for now. This feature is being removed by major browsers and '253 'deprecated by RFC 2818. (See https://github.com/shazow/urllib3/issues/497 '254 'for details.)'.format(hostname)),255 SubjectAltNameWarning256 )257 match_hostname(cert, self.assert_hostname or hostname)258259 self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED
9 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+31 added-14 removed
15 unmodified lines
16from .exceptions import (17 ClosedPoolError,18 ProtocolError,19 EmptyPoolError,20 HeaderParsingError,21 HostChangedError,22 LocationValueError,23 MaxRetryError,24 ProxyError,
13 unmodified lines
38from .request import RequestMethods39from .response import HTTPResponse4041from .util.connection import is_connection_dropped42from .util.response import assert_header_parsing43from .util.retry import Retry44from .util.timeout import Timeout43from .util.url import get_host45from .util.url import get_host, Url464748xrange = six.moves.xrange49
71 unmodified lines
121 been parsed, this is always a `urllib3.util.Timeout` object.122123 :param maxsize:124 Number of connections to save that can be reused. More than 1 is useful123 in multithreaded situations. If ``block`` is set to false, more125 in multithreaded situations. If ``block`` is set to False, more126 connections will be created but they will not be saved once they've127 been used.128129 :param block:
252 unmodified lines
382 http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')383 log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,384 httplib_response.status,385 httplib_response.length))386387 try:388 assert_header_parsing(httplib_response.msg)389 except HeaderParsingError as hpe: # Platform-specific: Python 3390 log.warning(391 'Failed to parse headers (url=%s): %s',392 self._absolute_url(url), hpe, exc_info=True)393394 return httplib_response395396 def _absolute_url(self, path):397 return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url398399 def close(self):400 """401 Close all pooled connections and disable the pool.402 """
18 unmodified lines
421 return True422423 # TODO: Add optional support for socket.gethostbyname checking.424 scheme, host, port = get_host(url)412425 426 # Use explicit default port for comparison when none is given427 if self.port and not port:428 port = port_by_scheme.get(scheme)429 elif not self.port and port == port_by_scheme.get(scheme):
150 unmodified lines
580 except (BaseSSLError, CertificateError) as e:581 # Close the connection. If a connection is reused on which there582 # was a Certificate error, the next request will certainly raise583 # another Certificate error.571 if conn:572 conn.close()573 conn = None584 conn = conn and conn.close()585 release_conn = True586 raise SSLError(e)587588 except SSLError:589 # Treat SSLError separately from BaseSSLError to preserve590 # traceback.579 if conn:580 conn.close()581 conn = None591 conn = conn and conn.close()592 release_conn = True593 raise594595 except (TimeoutError, HTTPException, SocketError, ConnectionError) as e:585 if conn:586 # Discard the connection for these exceptions. It will be587 # be replaced during the next _get_conn() call.588 conn.close()589 conn = None596 # Discard the connection for these exceptions. It will be597 # be replaced during the next _get_conn() call.598 conn = conn and conn.close()599 release_conn = True600601 if isinstance(e, SocketError) and self.proxy:602 e = ProxyError('Cannot connect to proxy.', e)603 elif isinstance(e, (SocketError, HTTPException)):
31 unmodified lines
635 try:636 retries = retries.increment(method, url, response=response, _pool=self)637 except MaxRetryError:638 if retries.raise_on_redirect:639 # Release the connection for this response, since we're not640 # returning it to be released manually.641 response.release_conn()642 raise643 return response644645 log.info("Redirecting %s -> %s" % (url, redirect_location))
49 unmodified lines
695696 HTTPConnectionPool.__init__(self, host, port, strict, timeout, maxsize,697 block, headers, retries, _proxy, _proxy_headers,698 **conn_kw)699700 if ca_certs and cert_reqs is None:701 cert_reqs = 'CERT_REQUIRED'702703 self.key_file = key_file704 self.cert_file = cert_file705 self.cert_reqs = cert_reqs706 self.ca_certs = ca_certs
106 unmodified lines
modified:requests/packages/urllib3/exceptions.py+21 added
147 unmodified lines
148 "Warned when perfoming security reducing actions"149 pass150151152class SubjectAltNameWarning(SecurityWarning):153 "Warned when connecting to a host with a certificate missing a SAN."154 pass155156157class InsecureRequestWarning(SecurityWarning):158 "Warned when making an unverified HTTPS request."159 pass160
10 unmodified lines
171172class ResponseNotChunked(ProtocolError, ValueError):173 "Response needs to be chunked in order to read it as chunks."174 pass175176177class ProxySchemeUnknown(AssertionError, ValueError):178 "ProxyManager does not support the supplied scheme"179 # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.180181 def __init__(self, scheme):182 message = "Not supported proxy scheme %s" % scheme183 super(ProxySchemeUnknown, self).__init__(message)184185186class HeaderParsingError(HTTPError):187 "Raised by assert_header_parsing, but we convert it to a log.warning statement."188 def __init__(self, defects, unparsed_data):189 message = '%s, unparsed data: %r' % (defects or 'Unknown', unparsed_data)190 super(HeaderParsingError, self).__init__(message)
modified:requests/packages/urllib3/poolmanager.py+3 added-3 removed
6 unmodified lines
78from ._collections import RecentlyUsedContainer9from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool10from .connectionpool import port_by_scheme11from .exceptions import LocationValueError, MaxRetryError11from .exceptions import LocationValueError, MaxRetryError, ProxySchemeUnknown12from .request import RequestMethods13from .util.url import parse_url14from .util.retry import Retry15
210 unmodified lines
226 if not proxy.port:227 port = port_by_scheme.get(proxy.scheme, 80)228 proxy = proxy._replace(port=port)229230 assert proxy.scheme in ("http", "https"), \231 'Not supported proxy scheme %s' % proxy.scheme230 if proxy.scheme not in ("http", "https"):231 raise ProxySchemeUnknown(proxy.scheme)232233 self.proxy = proxy234 self.proxy_headers = proxy_headers or {}235
45 unmodified lines
modified:requests/packages/urllib3/request.py+10 added-2 removed
69 unmodified lines
70 return self.request_encode_body(method, url, fields=fields,71 headers=headers,72 **urlopen_kw)7374 def request_encode_url(self, method, url, fields=None, **urlopen_kw):74 def request_encode_url(self, method, url, fields=None, headers=None,75 **urlopen_kw):76 """77 Make a request using :meth:`urlopen` with the ``fields`` encoded in78 the url. This is useful for request methods like GET, HEAD, DELETE, etc.79 """80 if headers is None:81 headers = self.headers8283 extra_kw = {'headers': headers}84 extra_kw.update(urlopen_kw)8586 if fields:87 url += '?' + urlencode(fields)81 return self.urlopen(method, url, **urlopen_kw)8889 return self.urlopen(method, url, **extra_kw)9091 def request_encode_body(self, method, url, fields=None, headers=None,92 encode_multipart=True, multipart_boundary=None,93 **urlopen_kw):94 """
55 unmodified lines
modified:requests/packages/urllib3/response.py+85 added-63 removed
1try:2 import http.client as httplib3except ImportError:4 import httplib5from contextlib import contextmanager6import zlib7import io8from socket import timeout as SocketTimeout9
2 unmodified lines
12 ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked13)14from .packages.six import string_types as basestring, binary_type, PY315from .connection import HTTPException, BaseSSLError15from .util.response import is_fp_closed16from .util.response import is_fp_closed, is_response_to_head171819class DeflateDecoder(object):20
181 unmodified lines
202 data += buf + self._decoder.flush()203204 return data205206 @contextmanager207 def _error_catcher(self):208 """209 Catch low-level python exceptions, instead re-raising urllib3210 variants, so that low-level exceptions are not leaked in the211 high-level api.212213 On exit, release the connection back to the pool.214 """215 try:216 try:217 yield218219 except SocketTimeout:220 # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but221 # there is yet no clean way to get at it from this context.222 raise ReadTimeoutError(self._pool, None, 'Read timed out.')223224 except BaseSSLError as e:225 # FIXME: Is there a better way to differentiate between SSLErrors?226 if 'read operation timed out' not in str(e): # Defensive:227 # This shouldn't happen but just in case we're missing an edge228 # case, let's avoid swallowing SSL errors.229 raise230231 raise ReadTimeoutError(self._pool, None, 'Read timed out.')232233 except HTTPException as e:234 # This includes IncompleteRead.235 raise ProtocolError('Connection broken: %r' % e, e)236 except Exception:237 # The response may not be closed but we're not going to use it anymore238 # so close it now to ensure that the connection is released back to the pool.239 if self._original_response and not self._original_response.isclosed():240 self._original_response.close()241242 raise243 finally:244 if self._original_response and self._original_response.isclosed():245 self.release_conn()246247 def read(self, amt=None, decode_content=None, cache_content=False):248 """249 Similar to :meth:`httplib.HTTPResponse.read`, but with two additional250 parameters: ``decode_content`` and ``cache_content``.
21 unmodified lines
272 if self._fp is None:273 return274275 flush_decoder = False276 data = None277235 try:236 try:237 if amt is None:238 # cStringIO doesn't like amt=None239 data = self._fp.read()278 with self._error_catcher():279 if amt is None:280 # cStringIO doesn't like amt=None281 data = self._fp.read()282 flush_decoder = True283 else:284 cache_content = False285 data = self._fp.read(amt)286 if amt != 0 and not data: # Platform-specific: Buggy versions of Python.287 # Close the connection when no data is returned288 #289 # This is redundant to what httplib/http.client _should_290 # already do. However, versions of python released before291 # December 15, 2012 (http://bugs.python.org/issue16298) do292 # not properly close the connection in all cases. There is293 # no harm in redundantly calling close.294 self._fp.close()295 flush_decoder = True241 else:242 cache_content = False243 data = self._fp.read(amt)244 if amt != 0 and not data: # Platform-specific: Buggy versions of Python.245 # Close the connection when no data is returned246 #247 # This is redundant to what httplib/http.client _should_248 # already do. However, versions of python released before249 # December 15, 2012 (http://bugs.python.org/issue16298) do250 # not properly close the connection in all cases. There is251 # no harm in redundantly calling close.252 self._fp.close()253 flush_decoder = True296255 except SocketTimeout:256 # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but257 # there is yet no clean way to get at it from this context.258 raise ReadTimeoutError(self._pool, None, 'Read timed out.')259260 except BaseSSLError as e:261 # FIXME: Is there a better way to differentiate between SSLErrors?262 if 'read operation timed out' not in str(e): # Defensive:263 # This shouldn't happen but just in case we're missing an edge264 # case, let's avoid swallowing SSL errors.265 raise266267 raise ReadTimeoutError(self._pool, None, 'Read timed out.')268269 except HTTPException as e:270 # This includes IncompleteRead.271 raise ProtocolError('Connection broken: %r' % e, e)272297 if data:298 self._fp_bytes_read += len(data)299300 data = self._decode(data, decode_content, flush_decoder)301302 if cache_content:303 self._body = data304280 return data305 return data306282 finally:283 if self._original_response and self._original_response.isclosed():284 self.release_conn()307308 def stream(self, amt=2**16, decode_content=None):309 """310 A generator wrapper for the read() method. A call will block until
29 unmodified lines
340 Remaining parameters are passed to the HTTPResponse constructor, along341 with ``original_response=r``.342 """343 headers = r.msg344345 if not isinstance(headers, HTTPHeaderDict):346 if PY3: # Python 3347 headers = HTTPHeaderDict(headers.items())348 else: # Python 2
110 unmodified lines
459 if not self.chunked:460 raise ResponseNotChunked("Response is not chunked. "461 "Header 'transfer-encoding: chunked' is missing.")462440 if self._original_response and self._original_response._method.upper() == 'HEAD':441 # Don't bother reading the body of a HEAD request.442 # FIXME: Can we do this somehow without accessing private httplib _method?463 # Don't bother reading the body of a HEAD request.464 if self._original_response and is_response_to_head(self._original_response):465 self._original_response.close()466 return467468 with self._error_catcher():446 while True:447 self._update_chunk_length()448 if self.chunk_left == 0:449 break450 chunk = self._handle_chunk(amt)451 yield self._decode(chunk, decode_content=decode_content,452 flush_decoder=True)469 while True:470 self._update_chunk_length()471 if self.chunk_left == 0:472 break473 chunk = self._handle_chunk(amt)474 yield self._decode(chunk, decode_content=decode_content,475 flush_decoder=True)476454 # Chunk content ends with \r\n: discard it.455 while True:456 line = self._fp.fp.readline()457 if not line:458 # Some sites may not end with '\r\n'.459 break460 if line == b'\r\n':461 break477 # Chunk content ends with \r\n: discard it.478 while True:479 line = self._fp.fp.readline()480 if not line:481 # Some sites may not end with '\r\n'.482 break483 if line == b'\r\n':484 break485463 # We read everything; close the "file".464 if self._original_response:465 self._original_response.close()466 self.release_conn()486 # We read everything; close the "file".487 if self._original_response:488 self._original_response.close()