Skip to content
Myr

Merge pull request #2142 from sigmavirus24/urllib3-1.9

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

Upgrade urllib3 to 1.9.x

authored by Kenneth Reitz · committed by Kenneth Reitz · parents 9575d6a, 170d626 · Browse files · 21 files+818 added−544 removed
This commit

State

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

Diff stats

21 files+818 added−544 removed

  • other:+818 added−544 removed

21 files+818 added−544 removed

modified:requests/packages/urllib3/contrib/ntlmpool.py-6 removed
1# urllib3/contrib/ntlmpool.py2# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php61"""2NTLM authenticating pool, contributed by erikcederstran34Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10
110 unmodified lines
modified:requests/packages/urllib3/contrib/pyopenssl.py+21 added-181 removed
52 unmodified lines
53from pyasn1.type import univ, constraint54from socket import _fileobject, timeout55import ssl56import select57from cStringIO import StringIO5758from .. import connection59from .. import util60
92 unmodified lines
153154 return dns_name155156158class fileobject(_fileobject):159160 def _wait_for_sock(self):161 rd, wd, ed = select.select([self._sock], [], [],162 self._sock.gettimeout())163 if not rd:164 raise timeout()165166167 def read(self, size=-1):168 # Use max, disallow tiny reads in a loop as they are very inefficient.169 # We never leave read() with any leftover data from a new recv() call170 # in our internal buffer.171 rbufsize = max(self._rbufsize, self.default_bufsize)172 # Our use of StringIO rather than lists of string objects returned by173 # recv() minimizes memory usage and fragmentation that occurs when174 # rbufsize is large compared to the typical return value of recv().175 buf = self._rbuf176 buf.seek(0, 2) # seek end177 if size < 0:178 # Read until EOF179 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.180 while True:181 try:182 data = self._sock.recv(rbufsize)183 except OpenSSL.SSL.WantReadError:184 self._wait_for_sock()185 continue186 if not data:187 break188 buf.write(data)189 return buf.getvalue()190 else:191 # Read until size bytes or EOF seen, whichever comes first192 buf_len = buf.tell()193 if buf_len >= size:194 # Already have size bytes in our buffer? Extract and return.195 buf.seek(0)196 rv = buf.read(size)197 self._rbuf = StringIO()198 self._rbuf.write(buf.read())199 return rv200201 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.202 while True:203 left = size - buf_len204 # recv() will malloc the amount of memory given as its205 # parameter even though it often returns much less data206 # than that. The returned data string is short lived207 # as we copy it into a StringIO and free it. This avoids208 # fragmentation issues on many platforms.209 try:210 data = self._sock.recv(left)211 except OpenSSL.SSL.WantReadError:212 self._wait_for_sock()213 continue214 if not data:215 break216 n = len(data)217 if n == size and not buf_len:218 # Shortcut. Avoid buffer data copies when:219 # - We have no data in our buffer.220 # AND221 # - Our call to recv returned exactly the222 # number of bytes we were asked to read.223 return data224 if n == left:225 buf.write(data)226 del data # explicit free227 break228 assert n <= left, "recv(%d) returned %d bytes" % (left, n)229 buf.write(data)230 buf_len += n231 del data # explicit free232 #assert buf_len == buf.tell()233 return buf.getvalue()234235 def readline(self, size=-1):236 buf = self._rbuf237 buf.seek(0, 2) # seek end238 if buf.tell() > 0:239 # check if we already have it in our buffer240 buf.seek(0)241 bline = buf.readline(size)242 if bline.endswith('\n') or len(bline) == size:243 self._rbuf = StringIO()244 self._rbuf.write(buf.read())245 return bline246 del bline247 if size < 0:248 # Read until \n or EOF, whichever comes first249 if self._rbufsize <= 1:250 # Speed up unbuffered case251 buf.seek(0)252 buffers = [buf.read()]253 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.254 data = None255 recv = self._sock.recv256 while True:257 try:258 while data != "\n":259 data = recv(1)260 if not data:261 break262 buffers.append(data)263 except OpenSSL.SSL.WantReadError:264 self._wait_for_sock()265 continue266 break267 return "".join(buffers)268269 buf.seek(0, 2) # seek end270 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.271 while True:272 try:273 data = self._sock.recv(self._rbufsize)274 except OpenSSL.SSL.WantReadError:275 self._wait_for_sock()276 continue277 if not data:278 break279 nl = data.find('\n')280 if nl >= 0:281 nl += 1282 buf.write(data[:nl])283 self._rbuf.write(data[nl:])284 del data285 break286 buf.write(data)287 return buf.getvalue()288 else:289 # Read until size bytes or \n or EOF seen, whichever comes first290 buf.seek(0, 2) # seek end291 buf_len = buf.tell()292 if buf_len >= size:293 buf.seek(0)294 rv = buf.read(size)295 self._rbuf = StringIO()296 self._rbuf.write(buf.read())297 return rv298 self._rbuf = StringIO() # reset _rbuf. we consume it via buf.299 while True:300 try:301 data = self._sock.recv(self._rbufsize)302 except OpenSSL.SSL.WantReadError:303 self._wait_for_sock()304 continue305 if not data:306 break307 left = size - buf_len308 # did we just receive a newline?309 nl = data.find('\n', 0, left)310 if nl >= 0:311 nl += 1312 # save the excess data to _rbuf313 self._rbuf.write(data[nl:])314 if buf_len:315 buf.write(data[:nl])316 break317 else:318 # Shortcut. Avoid data copy through buf when returning319 # a substring of our first recv().320 return data[:nl]321 n = len(data)322 if n == size and not buf_len:323 # Shortcut. Avoid data copy through buf when324 # returning exactly all of our first recv().325 return data326 if n >= left:327 buf.write(data[:left])328 self._rbuf.write(data[left:])329 break330 buf.write(data)331 buf_len += n332 #assert buf_len == buf.tell()333 return buf.getvalue()334335157class WrappedSocket(object):158 '''API-compatibility wrapper for Python OpenSSL's Connection-class.'''159339 def __init__(self, connection, socket):160 def __init__(self, connection, socket, suppress_ragged_eofs=True):161 self.connection = connection162 self.socket = socket163 self.suppress_ragged_eofs = suppress_ragged_eofs164165 def fileno(self):166 return self.socket.fileno()167168 def makefile(self, mode, bufsize=-1):347 return fileobject(self.connection, mode, bufsize)169 return _fileobject(self, mode, bufsize)170171 def recv(self, *args, **kwargs):172 try:173 data = self.connection.recv(*args, **kwargs)174 except OpenSSL.SSL.SysCallError as e:175 if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):176 return b''177 else:178 raise179 except OpenSSL.SSL.WantReadError:180 rd, wd, ed = select.select(181 [self.socket], [], [], self.socket.gettimeout())182 if not rd:183 raise timeout()184 else:185 return self.recv(*args, **kwargs)186 else:187 return data188189 def settimeout(self, timeout):190 return self.socket.settimeout(timeout)191192 def sendall(self, data):
70 unmodified lines
modified:requests/packages/urllib3/packages/ordered_dict.py-1 removed
1# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.2# Passes Python2.7's test suite and incorporates all the latest updates.3# Copyright 2009 Raymond Hettinger, released under the MIT License.4# http://code.activestate.com/recipes/576693/55try:6 from thread import get_ident as _get_ident7except ImportError:8 from dummy_thread import get_ident as _get_ident
251 unmodified lines
modified:requests/packages/urllib3/util/__init__.py+3 added-6 removed
1# urllib3/util/__init__.py2# Copyright 2008-2014 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php61# For backwards compatibility, provide imports that used to be here.2from .connection import is_connection_dropped3from .request import make_headers4from .response import is_fp_closed5from .ssl_ import (
7 unmodified lines
13from .timeout import (14 current_time,15 Timeout,16)1718from .retry import Retry19from .url import (20 get_host,21 parse_url,22 split_first,
2 unmodified lines
modified:requests/packages/urllib3/util/connection.py+55 added-3 removed
1from socket import error as SocketError1import socket2try:3 from select import poll, POLLIN4except ImportError: # `poll` doesn't exist on OSX and other platforms5 poll = False
1 unmodified line
7 from select import select8 except ImportError: # `select` doesn't exist on AppEngine.9 select = False101112def is_connection_dropped(conn): # Platform-specific13 """14 Returns True if the connection is dropped and should be closed.15
6 unmodified lines
22 sock = getattr(conn, 'sock', False)23 if sock is False: # Platform-specific: AppEngine24 return False25 if sock is None: # Connection already closed (such as by httplib).25 return False26 return True2728 if not poll:29 if not select: # Platform-specific: AppEngine30 return False3132 try:33 return select([sock], [], [], 0.0)[0]33 except SocketError:34 except socket.error:35 return True3637 # This version is better on platforms that support it.38 p = poll()
3 unmodified lines
42 # Either data is buffered (bad), or the connection is dropped.43 return True444546# This function is copied from socket.py in the Python 2.7 standard47# library test suite. Added to its signature is only `socket_options`.48def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,49 source_address=None, socket_options=None):50 """Connect to *address* and return the socket object.5152 Convenience function. Connect to *address* (a 2-tuple ``(host,53 port)``) and return the socket object. Passing the optional54 *timeout* parameter will set the timeout on the socket instance55 before attempting to connect. If no *timeout* is supplied, the56 global default timeout setting returned by :func:`getdefaulttimeout`57 is used. If *source_address* is set it must be a tuple of (host, port)58 for the socket to bind as a source address before making the connection.59 An host of '' or port 0 tells the OS to use the default.60 """6162 host, port = address63 err = None64 for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):65 af, socktype, proto, canonname, sa = res66 sock = None67 try:68 sock = socket.socket(af, socktype, proto)6970 # If provided, set socket level options before connecting.71 # This is the only addition urllib3 makes to this function.72 _set_socket_options(sock, socket_options)7374 if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:75 sock.settimeout(timeout)76 if source_address:77 sock.bind(source_address)78 sock.connect(sa)79 return sock8081 except socket.error as _:82 err = _83 if sock is not None:84 sock.close()8586 if err is not None:87 raise err88 else:89 raise socket.error("getaddrinfo returns an empty list")909192def _set_socket_options(sock, options):93 if options is None:94 return9596 for opt in options:97 sock.setsockopt(*opt)
modified:requests/packages/urllib3/util/request.py+11 added-8 removed
1from base64 import b64encode23from ..packages import six3from ..packages.six import b455ACCEPT_ENCODING = 'gzip,deflate'678def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,10 basic_auth=None, proxy_basic_auth=None):9 basic_auth=None, proxy_basic_auth=None, disable_cache=None):10 """11 Shortcuts for generating request headers.1213 :param keep_alive:
16 unmodified lines
30 :param proxy_basic_auth:31 Colon-separated username:password string for 'proxy-authorization: basic ...'32 auth header.3335 Example: ::34 :param disable_cache:35 If ``True``, adds 'cache-control: no-cache' header.3637 Example::3839 >>> make_headers(keep_alive=True, user_agent="Batman/1.0")40 {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}41 >>> make_headers(accept_encoding=True)42 {'accept-encoding': 'gzip,deflate'}
15 unmodified lines
58 headers['connection'] = 'keep-alive'5960 if basic_auth:61 headers['authorization'] = 'Basic ' + \60 b64encode(six.b(basic_auth)).decode('utf-8')62 b64encode(b(basic_auth)).decode('utf-8')6364 if proxy_basic_auth:65 headers['proxy-authorization'] = 'Basic ' + \64 b64encode(six.b(proxy_basic_auth)).decode('utf-8')66 b64encode(b(proxy_basic_auth)).decode('utf-8')6766 return headers68 if disable_cache:69 headers['cache-control'] = 'no-cache'706871 return headers
added:requests/packages/urllib3/util/retry.py+279 added
1import time2import logging34from ..exceptions import (5 ProtocolError,6 ConnectTimeoutError,7 ReadTimeoutError,8 MaxRetryError,9)10from ..packages import six111213log = logging.getLogger(__name__)141516class Retry(object):17 """ Retry configuration.1819 Each retry attempt will create a new Retry object with updated values, so20 they can be safely reused.2122 Retries can be defined as a default for a pool::2324 retries = Retry(connect=5, read=2, redirect=5)25 http = PoolManager(retries=retries)26 response = http.request('GET', 'http://example.com/')2728 Or per-request (which overrides the default for the pool)::2930 response = http.request('GET', 'http://example.com/', retries=Retry(10))3132 Retries can be disabled by passing ``False``::3334 response = http.request('GET', 'http://example.com/', retries=False)3536 Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless37 retries are disabled, in which case the causing exception will be raised.383940 :param int total:41 Total number of retries to allow. Takes precedence over other counts.4243 Set to ``None`` to remove this constraint and fall back on other44 counts. It's a good idea to set this to some sensibly-high value to45 account for unexpected edge cases and avoid infinite retry loops.4647 Set to ``0`` to fail on the first retry.4849 Set to ``False`` to disable and imply ``raise_on_redirect=False``.5051 :param int connect:52 How many connection-related errors to retry on.5354 These are errors raised before the request is sent to the remote server,55 which we assume has not triggered the server to process the request.5657 Set to ``0`` to fail on the first retry of this type.5859 :param int read:60 How many times to retry on read errors.6162 These errors are raised after the request was sent to the server, so the63 request may have side-effects.6465 Set to ``0`` to fail on the first retry of this type.6667 :param int redirect:68 How many redirects to perform. Limit this to avoid infinite redirect69 loops.7071 A redirect is a HTTP response with a status code 301, 302, 303, 307 or72 308.7374 Set to ``0`` to fail on the first retry of this type.7576 Set to ``False`` to disable and imply ``raise_on_redirect=False``.7778 :param iterable method_whitelist:79 Set of uppercased HTTP method verbs that we should retry on.8081 By default, we only retry on methods which are considered to be82 indempotent (multiple requests with the same parameters end with the83 same state). See :attr:`Retry.DEFAULT_METHOD_WHITELIST`.8485 :param iterable status_forcelist:86 A set of HTTP status codes that we should force a retry on. 8788 By default, this is disabled with ``None``.8990 :param float backoff_factor:91 A backoff factor to apply between attempts. urllib3 will sleep for::9293 {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`.9899 By default, backoff is disabled (set to 0).100101 :param bool raise_on_redirect: Whether, if the number of redirects is102 exhausted, to raise a MaxRetryError, or to return a response with a103 response code in the 3xx range.104 """105106 DEFAULT_METHOD_WHITELIST = frozenset([107 'HEAD', 'GET', 'PUT', 'DELETE', 'OPTIONS', 'TRACE'])108109 #: Maximum backoff time.110 BACKOFF_MAX = 120111112 def __init__(self, total=10, connect=None, read=None, redirect=None,113 method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None,114 backoff_factor=0, raise_on_redirect=True, _observed_errors=0):115116 self.total = total117 self.connect = connect118 self.read = read119120 if redirect is False or total is False:121 redirect = 0122 raise_on_redirect = False123124 self.redirect = redirect125 self.status_forcelist = status_forcelist or set()126 self.method_whitelist = method_whitelist127 self.backoff_factor = backoff_factor128 self.raise_on_redirect = raise_on_redirect129 self._observed_errors = _observed_errors # TODO: use .history instead?130131 def new(self, **kw):132 params = dict(133 total=self.total,134 connect=self.connect, read=self.read, redirect=self.redirect,135 method_whitelist=self.method_whitelist,136 status_forcelist=self.status_forcelist,137 backoff_factor=self.backoff_factor,138 raise_on_redirect=self.raise_on_redirect,139 _observed_errors=self._observed_errors,140 )141 params.update(kw)142 return type(self)(**params)143144 @classmethod145 def from_int(cls, retries, redirect=True, default=None):146 """ Backwards-compatibility for the old retries format."""147 if retries is None:148 retries = default if default is not None else cls.DEFAULT149150 if isinstance(retries, Retry):151 return retries152153 redirect = bool(redirect) and None154 new_retries = cls(retries, redirect=redirect)155 log.debug("Converted retries value: %r -> %r" % (retries, new_retries))156 return new_retries157158 def get_backoff_time(self):159 """ Formula for computing the current backoff160161 :rtype: float162 """163 if self._observed_errors <= 1:164 return 0165166 backoff_value = self.backoff_factor * (2 ** (self._observed_errors - 1))167 return min(self.BACKOFF_MAX, backoff_value)168169 def sleep(self):170 """ Sleep between retry attempts using an exponential backoff.171172 By default, the backoff factor is 0 and this method will return173 immediately.174 """175 backoff = self.get_backoff_time()176 if backoff <= 0:177 return178 time.sleep(backoff)179180 def _is_connection_error(self, err):181 """ Errors when we're fairly sure that the server did not receive the182 request, so it should be safe to retry.183 """184 return isinstance(err, ConnectTimeoutError)185186 def _is_read_error(self, err):187 """ Errors that occur after the request has been started, so we can't188 assume that the server did not process any of it.189 """190 return isinstance(err, (ReadTimeoutError, ProtocolError))191192 def is_forced_retry(self, method, status_code):193 """ Is this method/response retryable? (Based on method/codes whitelists)194 """195 if self.method_whitelist and method.upper() not in self.method_whitelist:196 return False197198 return self.status_forcelist and status_code in self.status_forcelist199200 def is_exhausted(self):201 """ Are we out of retries?202 """203 retry_counts = (self.total, self.connect, self.read, self.redirect)204 retry_counts = list(filter(None, retry_counts))205 if not retry_counts:206 return False207208 return min(retry_counts) < 0209210 def increment(self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None):211 """ Return a new Retry object with incremented retry counters.212213 :param response: A response object, or None, if the server did not214 return a response.215 :type response: :class:`~urllib3.response.HTTPResponse`216 :param Exception error: An error encountered during the request, or217 None if the response was received successfully.218219 :return: A new ``Retry`` object.220 """221 if self.total is False and error:222 # Disabled, indicate to re-raise the error.223 raise six.reraise(type(error), error, _stacktrace)224225 total = self.total226 if total is not None:227 total -= 1228229 _observed_errors = self._observed_errors230 connect = self.connect231 read = self.read232 redirect = self.redirect233234 if error and self._is_connection_error(error):235 # Connect retry?236 if connect is False:237 raise six.reraise(type(error), error, _stacktrace)238 elif connect is not None:239 connect -= 1240 _observed_errors += 1241242 elif error and self._is_read_error(error):243 # Read retry?244 if read is False:245 raise six.reraise(type(error), error, _stacktrace)246 elif read is not None:247 read -= 1248 _observed_errors += 1249250 elif response and response.get_redirect_location():251 # Redirect retry?252 if redirect is not None:253 redirect -= 1254255 else:256 # FIXME: Nothing changed, scenario doesn't make sense.257 _observed_errors += 1258259 new_retry = self.new(260 total=total,261 connect=connect, read=read, redirect=redirect,262 _observed_errors=_observed_errors)263264 if new_retry.is_exhausted():265 raise MaxRetryError(_pool, url, error)266267 log.debug("Incremented Retry for (url='%s'): %r" % (url, new_retry))268269 return new_retry270271272 def __repr__(self):273 return ('{cls.__name__}(total={self.total}, connect={self.connect}, '274 'read={self.read}, redirect={self.redirect})').format(275 cls=type(self), self=self)276277278# For backwards compatibility (equivalent to pre-v1.9):279Retry.DEFAULT = Retry(3)
modified:requests/packages/urllib3/util/ssl_.py+2 added-3 removed
32 unmodified lines
33 20: sha134 }3536 fingerprint = fingerprint.replace(':', '').lower()37 digest_length, odd = divmod(len(fingerprint), 2)3838 digest_length, rest = divmod(len(fingerprint), 2)3940 if rest or digest_length not in hashfunc_map:39 if odd or digest_length not in hashfunc_map:40 raise SSLError('Fingerprint is of invalid length.')4142 # We need encode() here for py32; works on py2 and p33.43 fingerprint_bytes = unhexlify(fingerprint.encode())
89 unmodified lines
modified:requests/packages/urllib3/util/timeout.py+52 added-46 removed
1# The default socket timeout, used by httplib to indicate that no timeout was2# specified by the user3from socket import _GLOBAL_DEFAULT_TIMEOUT4import time56from ..exceptions import TimeoutStateError78# A sentinel value to indicate that no timeout was specified by the user in9# urllib310_Default = object()1112def current_time():13 """9 Retrieve the current time, this function is mocked out in unit testing.14 Retrieve the current time. This function is mocked out in unit testing.15 """16 return time.time()171814_Default = object()15# The default timeout to use for socket connections. This is the attribute used16# by httplib to define the default timeout19class Timeout(object):20 """ Timeout configuration.2122 Timeouts can be defined as a default for a pool::2319class Timeout(object):20 """21 Utility object for storing timeout values.24 timeout = Timeout(connect=2.0, read=7.0)25 http = PoolManager(timeout=timeout)26 response = http.request('GET', 'http://example.com/')2723 Example usage:28 Or per-request (which overrides the default for the pool)::2925 .. code-block:: python30 response = http.request('GET', 'http://example.com/', timeout=Timeout(10))3127 timeout = urllib3.util.Timeout(connect=2.0, read=7.0)28 pool = HTTPConnectionPool('www.google.com', 80, timeout=timeout)29 pool.request(...) # Etc, etc32 Timeouts can be disabled by setting all the parameters to ``None``::3334 no_timeout = Timeout(connect=None, read=None)35 response = http.request('GET', 'http://example.com/, timeout=no_timeout)363738 :param total:39 This combines the connect and read timeouts into one; the read timeout40 will be set to the time leftover from the connect attempt. In the41 event that both a connect timeout and a total are specified, or a read42 timeout and a total are specified, the shorter timeout will be applied.4344 Defaults to None.4546 :type total: integer, float, or None4748 :param connect:49 The maximum amount of time to wait for a connection attempt to a server50 to succeed. Omitting the parameter will default the connect timeout to51 the system default, probably `the global default timeout in socket.py
11 unmodified lines
63 None will set an infinite timeout.6465 :type read: integer, float, or None6650 :param total:51 This combines the connect and read timeouts into one; the read timeout52 will be set to the time leftover from the connect attempt. In the53 event that both a connect timeout and a total are specified, or a read54 timeout and a total are specified, the shorter timeout will be applied.5556 Defaults to None.5758 :type total: integer, float, or None5967 .. note::6869 Many factors can affect the total amount of time for urllib3 to return63 an HTTP response. Specifically, Python's DNS resolver does not obey the64 timeout specified on the socket. Other factors that can affect total65 request time include high CPU load, high swap, the program running at a66 low priority level, or other behaviors. The observed running time for67 urllib3 to return a response may be greater than the value passed to68 `total`.70 an HTTP response.7172 For example, Python's DNS resolver does not obey the timeout specified73 on the socket. Other factors that can affect total request time include74 high CPU load, high swap, the program running at a low priority level,75 or other behaviors.7677 In addition, the read and total timeouts only measure the time between78 read operations on the socket connecting the client and the server,79 not the total amount of time for the request to return a complete80 response. For most requests, the timeout is raised because the server81 has not sent the first byte in the specified time. This is not always82 the case; if a server streams one byte every fifteen seconds, a timeout76 of 20 seconds will not ever trigger, even though the request will77 take several minutes to complete.83 of 20 seconds will not trigger, even though the request will take84 several minutes to complete.8586 If your goal is to cut off any request after a set amount of wall clock87 time, consider having a second "watcher" thread to cut off a slow88 request.
11 unmodified lines
100 def __str__(self):101 return '%s(connect=%r, read=%r, total=%r)' % (102 type(self).__name__, self._connect, self._read, self.total)10397104 @classmethod105 def _validate_timeout(cls, value, name):100 """ Check that a timeout attribute is valid106 """ Check that a timeout attribute is valid.107108 :param value: The timeout value to validate103 :param name: The name of the timeout attribute to validate. This is used104 for clear error messages105 :return: the value106 :raises ValueError: if the type is not an integer or a float, or if it107 is a numeric value less than zero109 :param name: The name of the timeout attribute to validate. This is110 used to specify in error messages.111 :return: The validated and casted version of the given value.112 :raises ValueError: If the type is not an integer or a float, or if it113 is a numeric value less than zero.114 """115 if value is _Default:116 return cls.DEFAULT_TIMEOUT117
10 unmodified lines
128 if value < 0:129 raise ValueError("Attempted to set %s timeout to %s, but the "130 "timeout cannot be set to a value less "131 "than 0." % (name, value))126 except TypeError: # Python 3132 except TypeError: # Python 3133 raise ValueError("Timeout value %s was %s, but it must be an "134 "int or float." % (name, value))135136 return value
3 unmodified lines
140 """ Create a new Timeout from a legacy timeout value.141142 The timeout value used by httplib.py sets the same timeout on the143 connect(), and recv() socket requests. This creates a :class:`Timeout`138 object that sets the individual timeouts to the ``timeout`` value passed139 to this function.144 object that sets the individual timeouts to the ``timeout`` value145 passed to this function.146141 :param timeout: The legacy timeout value147 :param timeout: The legacy timeout value.148 :type timeout: integer, float, sentinel default object, or None143 :return: a Timeout object149 :return: Timeout object150 :rtype: :class:`Timeout`151 """152 return Timeout(read=timeout, connect=timeout)153
25 unmodified lines
179180 def get_connect_duration(self):181 """ Gets the time elapsed since the call to :meth:`start_connect`.182177 :return: the elapsed time183 :return: Elapsed time.184 :rtype: float185 :raises urllib3.exceptions.TimeoutStateError: if you attempt186 to get duration for a timer that hasn't been started.187 """
8 unmodified lines
196197 This will be a positive float or integer, the value None198 (never timeout), or the default system timeout.199194 :return: the connect timeout200 :return: Connect timeout.201 :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None202 """203 if self.total is None:204 return self._connect
14 unmodified lines
219 time taken by the connect timeout. If the connection time has not been220 established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be221 raised.222217 :return: the value to use for the read timeout223 :return: Value to use for the read timeout.224 :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None225 :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`226 has not yet been called on this object.227 """228 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):226 # in case the connect timeout has not yet been established.232 # In case the connect timeout has not yet been established.233 if self._start_connect is None:234 return self._read235 return max(0, min(self.total - self.get_connect_duration(),236 self._read))
4 unmodified lines
modified:requests/packages/urllib3/util/url.py+14 added-5 removed
1 unmodified line
23from ..exceptions import LocationParseError456class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):6url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']789class Url(namedtuple('Url', url_attrs)):10 """11 Datastructure for representing an HTTP URL. Used as a return value for12 :func:`parse_url`.13 """14 slots = ()1513 def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None, query=None, fragment=None):14 return super(Url, cls).__new__(cls, scheme, auth, host, port, path, query, fragment)16 def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None,17 query=None, fragment=None):18 return super(Url, cls).__new__(cls, scheme, auth, host, port, path,19 query, fragment)2021 @property22 def hostname(self):23 """For backwards-compatibility with urlparse. We're nice like that."""
23 unmodified lines
47 delimiter. Return two split parts and the matched delimiter.4849 If not found, then the first part is the full input string.5046 Example: ::51 Example::5253 >>> split_first('foo/bar?baz', '?/=')54 ('foo', 'bar?baz', '/')55 >>> split_first('foo/bar?baz', '123')
24 unmodified lines
80 performed to parse incomplete urls. Fields not provided will be None.8182 Partly backwards-compatible with :mod:`urlparse`.8379 Example: ::84 Example::8586 >>> parse_url('http://google.com/mail/')87 Url(scheme='http', host='google.com', port=None, path='/', ...)88 >>> parse_url('google.com:80')
6 unmodified lines
95 # simplified for our needs and less annoying.96 # Additionally, this implementations does silly things to be optimal97 # on CPython.9899 if not url:100 # Empty101 return Url()102103 scheme = None104 auth = None105 host = None106 port = None
65 unmodified lines
modified:requests/packages/urllib3/__init__.py+16 added-8 removed
1# urllib3/__init__.py2# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php61"""2urllib3 - Thread-safe connection pooling and re-using.3"""4
11 unmodified lines
16from . import exceptions17from .filepost import encode_multipart_formdata18from .poolmanager import PoolManager, ProxyManager, proxy_from_url19from .response import HTTPResponse26from .util import make_headers, get_host, Timeout20from .util.request import make_headers21from .util.url import get_host22from .util.timeout import Timeout23from .util.retry import Retry242526# Set default logging handler to avoid "No handler found" warnings.27import logging
19 unmodified lines
47 handler = logging.StreamHandler()48 handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))49 logger.addHandler(handler)50 logger.setLevel(level)54 logger.debug('Added an stderr logging handler to logger: %s' % __name__)51 logger.debug('Added a stderr logging handler to logger: %s' % __name__)52 return handler5354# ... Clean up.55del NullHandler565758# Set security warning to only go off once by default.59import warnings60warnings.simplefilter('module', exceptions.InsecureRequestWarning)6162def disable_warnings(category=exceptions.HTTPWarning):63 """64 Helper for quickly disabling all urllib3 warnings.65 """66 warnings.simplefilter('ignore', category)
modified:requests/packages/urllib3/_collections.py+1 added-7 removed
1# urllib3/_collections.py2# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php61from collections import Mapping, MutableMapping2try:3 from threading import RLock4except ImportError: # Platform-specific: No threads available
104 unmodified lines
109110 A ``dict`` like container for storing HTTP Headers.111112 Field names are stored and compared case-insensitively in compliance with119 RFC 2616. Iteration provides the first case-sensitive key seen for each113 RFC 7230. Iteration provides the first case-sensitive key seen for each114 case-insensitive pair.115116 Using ``__setitem__`` syntax overwrites fields that compare equal117 case-insensitively in order to maintain ``dict``'s api. For fields that
82 unmodified lines
modified:requests/packages/urllib3/connection.py+76 added-49 removed
1# urllib3/connection.py2# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php61import sys2import socket3from socket import timeout as SocketTimeout411try: # Python 35try: # Python 36 from http.client import HTTPConnection as _HTTPConnection, HTTPException7except ImportError:8 from httplib import HTTPConnection as _HTTPConnection, HTTPException91011class DummyConnection(object):12 "Used to detect a failed ConnectionCls import."13 pass1420try: # Compiled with SSL?21 ssl = None1516try: # Compiled with SSL?17 HTTPSConnection = DummyConnection18 import ssl19 BaseSSLError = ssl.SSLError20except (ImportError, AttributeError): # Platform-specific: No SSL.21 ssl = None2223 class BaseSSLError(BaseException):24 pass2527 try: # Python 328 from http.client import HTTPSConnection as _HTTPSConnection29 except ImportError:30 from httplib import HTTPSConnection as _HTTPSConnection2632 import ssl33 BaseSSLError = ssl.SSLError3435except (ImportError, AttributeError): # Platform-specific: No SSL.36 pass3727from .exceptions import (28 ConnectTimeoutError,29)30from .packages.ssl_match_hostname import match_hostname31from .packages import six43from .util import (44 assert_fingerprint,3233from .util.ssl_ import (34 resolve_cert_reqs,35 resolve_ssl_version,36 ssl_wrap_socket,37 assert_fingerprint,38)3940from .util import connection414243port_by_scheme = {44 'http': 80,45 'https': 443,46}
2 unmodified lines
49class HTTPConnection(_HTTPConnection, object):50 """51 Based on httplib.HTTPConnection but provides an extra constructor52 backwards-compatibility layer between older and newer Pythons.5354 Additional keyword parameters are used to configure attributes of the connection.55 Accepted parameters include:5657 - ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool`58 - ``source_address``: Set the source address for the current connection.5960 .. note:: This is ignored for Python 2.6. It is only applied for 2.7 and 3.x6162 - ``socket_options``: Set specific options on the underlying socket. If not specified, then63 defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling64 Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.6566 For example, if you wish to enable TCP Keep Alive in addition to the defaults,67 you might pass::6869 HTTPConnection.default_socket_options + [70 (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),71 ]7273 Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).74 """7576 default_port = port_by_scheme['http']7765 # By default, disable Nagle's Algorithm.66 tcp_nodelay = 178 #: Disable Nagle's algorithm by default.79 #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``80 default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]8182 #: Whether this connection verifies the host's certificate.83 is_verified = False8485 def __init__(self, *args, **kw):86 if six.PY3: # Python 387 kw.pop('strict', None)71 if sys.version_info < (2, 7): # Python 2.6 and older72 kw.pop('source_address', None)8889 # Pre-set source_address in case we have an older Python like 2.6.90 self.source_address = kw.get('source_address')9192 if sys.version_info < (2, 7): # Python 2.693 # _HTTPConnection on Python 2.6 will balk at this keyword arg, but94 # not newer versions. We can still use it when creating a95 # connection though, so we pop it *after* we have saved it as96 # self.source_address.97 kw.pop('source_address', None)9899 #: The socket options provided by the user. If no options are100 #: provided, we use the default options.101 self.socket_options = kw.pop('socket_options', self.default_socket_options)102103 # Superclass also sets self.source_address in Python 2.7+.78 _HTTPConnection.__init__(self, *args, **kw) 104 _HTTPConnection.__init__(self, *args, **kw)105106 def _new_conn(self):107 """ Establish a socket connection and set nodelay settings on it.10883 :return: a new socket connection109 :return: New socket connection.110 """85 extra_args = []86 if self.source_address: # Python 2.7+87 extra_args.append(self.source_address)111 extra_kw = {}112 if self.source_address:113 extra_kw['source_address'] = self.source_address11489 conn = socket.create_connection(90 (self.host, self.port), self.timeout, *extra_args)91 conn.setsockopt(92 socket.IPPROTO_TCP, socket.TCP_NODELAY, self.tcp_nodelay)115 if self.socket_options:116 extra_kw['socket_options'] = self.socket_options117118 try:119 conn = connection.create_connection(120 (self.host, self.port), self.timeout, **extra_kw)121122 except SocketTimeout:123 raise ConnectTimeoutError(124 self, "Connection to %s timed out. (connect timeout=%s)" %125 (self.host, self.timeout))126127 return conn128129 def _prepare_conn(self, conn):130 self.sock = conn
2 unmodified lines
133 # not have them.134 if getattr(self, '_tunnel_host', None):135 # TODO: Fix tunnel so it doesn't depend on self.sock state.136 self._tunnel()137 # Mark this connection as not reusable138 self.auto_open = 0139140 def connect(self):141 conn = self._new_conn()142 self._prepare_conn(conn)
28 unmodified lines
171 """172 cert_reqs = None173 ca_certs = None174 ssl_version = None140 conn_kw = {}175176 def set_cert(self, key_file=None, cert_file=None,177 cert_reqs=None, ca_certs=None,178 assert_hostname=None, assert_fingerprint=None):
6 unmodified lines
185 self.assert_fingerprint = assert_fingerprint186187 def connect(self):188 # Add certificate verification189 conn = self._new_conn()190156 try:157 sock = socket.create_connection(158 address=(self.host, self.port), timeout=self.timeout,159 **self.conn_kw)160 except SocketTimeout:161 raise ConnectTimeoutError(162 self, "Connection to %s timed out. (connect timeout=%s)" %163 (self.host, self.timeout))164165 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY,166 self.tcp_nodelay)167191 resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)192 resolved_ssl_version = resolve_ssl_version(self.ssl_version)193194 hostname = self.host195 if getattr(self, '_tunnel_host', None):196 # _tunnel_host was added in Python 2.6.3197 # (See: http://hg.python.org/cpython/rev/0f57b30a152f)198176 self.sock = sock199 self.sock = conn200 # Calls self._set_hostport(), so self.host is201 # self._tunnel_host below.202 self._tunnel()203 # Mark this connection as not reusable204 self.auto_open = 0205206 # Override the host with the one we're requesting data from.207 hostname = self._tunnel_host208209 # Wrap socket using verification with the root certs in210 # trusted_root_certs186 self.sock = ssl_wrap_socket(sock, self.key_file, self.cert_file,211 self.sock = ssl_wrap_socket(conn, self.key_file, self.cert_file,212 cert_reqs=resolved_cert_reqs,213 ca_certs=self.ca_certs,214 server_hostname=hostname,215 ssl_version=resolved_ssl_version)
5 unmodified lines
221 elif self.assert_hostname is not False:222 match_hostname(self.sock.getpeercert(),223 self.assert_hostname or hostname)224225 self.is_verified = resolved_cert_reqs == ssl.CERT_REQUIRED226227228if ssl:229 # Make a copy for testing.230 UnverifiedHTTPSConnection = HTTPSConnection231 HTTPSConnection = VerifiedHTTPSConnection
modified:requests/packages/urllib3/connectionpool.py+153 added-106 removed
1# urllib3/connectionpool.py2# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php67import sys1import errno2import logging3import sys4import warnings56from socket import error as SocketError, timeout as SocketTimeout7import socket814try: # Python 39try: # Python 310 from queue import LifoQueue, Empty, Full11except ImportError:12 from Queue import LifoQueue, Empty, Full13 import Queue as _ # Platform-specific: Windows141516from .exceptions import (17 ClosedPoolError,23 ConnectionError,24 ConnectTimeoutError,18 ProtocolError,19 EmptyPoolError,20 HostChangedError,27 LocationParseError,21 LocationValueError,22 MaxRetryError,23 ProxyError,24 ReadTimeoutError,25 SSLError,26 TimeoutError,31 ReadTimeoutError,32 ProxyError,27 InsecureRequestWarning,28)29from .packages.ssl_match_hostname import CertificateError30from .packages import six31from .connection import (
3 unmodified lines
35 HTTPException, BaseSSLError,36)37from .request import RequestMethods38from .response import HTTPResponse44from .util import (45 get_host,46 is_connection_dropped,47 Timeout,48)3940from .util.connection import is_connection_dropped41from .util.retry import Retry42from .util.timeout import Timeout43from .util.url import get_host444546xrange = six.moves.xrange4748log = logging.getLogger(__name__)4950_Default = object()5157## Pool objects5253## Pool objects54class ConnectionPool(object):55 """56 Base class for all connection pools, such as57 :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.
2 unmodified lines
60 scheme = None61 QueueCls = LifoQueue6263 def __init__(self, host, port=None):69 if host is None:70 raise LocationParseError(host)64 if not host:65 raise LocationValueError("No host specified.")6667 # httplib doesn't like it when we include brackets in ipv6 addresses73 host = host.strip('[]')7475 self.host = host68 self.host = host.strip('[]')69 self.port = port7071 def __str__(self):72 return '%s(host=%r, port=%r)' % (type(self).__name__,
1 unmodified line
7475# This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l25276_blocking_errnos = set([errno.EAGAIN, errno.EWOULDBLOCK])777879class HTTPConnectionPool(ConnectionPool, RequestMethods):80 """81 Thread-safe connection pool for one host.82
36 unmodified lines
119 :param headers:120 Headers to include with all requests, unless other headers are given121 explicitly.122123 :param retries:124 Retry configuration to use by default with requests in this pool.125126 :param _proxy:127 Parsed proxy URL, should not be used directly, instead, see128 :class:`urllib3.connectionpool.ProxyManager`"129130 :param _proxy_headers:131 A dictionary with proxy headers, should not be used directly,132 instead, see :class:`urllib3.connectionpool.ProxyManager`"133134 :param \**conn_kw:135 Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,136 :class:`urllib3.connection.HTTPSConnection` instances.137 """138139 scheme = 'http'140 ConnectionCls = HTTPConnection141142 def __init__(self, host, port=None, strict=False,143 timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False,143 headers=None, _proxy=None, _proxy_headers=None, **conn_kw):144 headers=None, retries=None,145 _proxy=None, _proxy_headers=None,146 **conn_kw):147 ConnectionPool.__init__(self, host, port)148 RequestMethods.__init__(self, headers)149150 self.strict = strict151149 # This is for backwards compatibility and can be removed once a timeout150 # can only be set to a Timeout object152 if not isinstance(timeout, Timeout):153 timeout = Timeout.from_float(timeout)154155 if retries is None:156 retries = Retry.DEFAULT157158 self.timeout = timeout159 self.retries = retries160161 self.pool = self.QueueCls(maxsize)162 self.block = block163
6 unmodified lines
170171 # These are mostly for testing and debugging purposes.172 self.num_connections = 0173 self.num_requests = 0169170 if sys.version_info < (2, 7): # Python 2.6 and older171 conn_kw.pop('source_address', None)174 self.conn_kw = conn_kw175176 if self.proxy:177 # Enable Nagle's algorithm for proxies, to avoid packet fragmentation.178 # We cannot know if the user has added default socket options, so we cannot replace the179 # list.180 self.conn_kw.setdefault('socket_options', [])181182 def _new_conn(self):183 """184 Return a fresh :class:`HTTPConnection`.185 """
3 unmodified lines
189190 conn = self.ConnectionCls(host=self.host, port=self.port,191 timeout=self.timeout.connect_timeout,192 strict=self.strict, **self.conn_kw)185 if self.proxy is not None:186 # Enable Nagle's algorithm for proxies, to avoid packet187 # fragmentation.188 conn.tcp_nodelay = 0193 return conn194195 def _get_conn(self, timeout=None):196 """
10 unmodified lines
207 conn = None208 try:209 conn = self.pool.get(block=self.block, timeout=timeout)210207 except AttributeError: # self.pool is None211 except AttributeError: # self.pool is None212 raise ClosedPoolError(self, "Pool is closed.")213214 except Empty:215 if self.block:
5 unmodified lines
221 # If this is a persistent connection, check if it got disconnected222 if conn and is_connection_dropped(conn):223 log.info("Resetting dropped connection: %s" % self.host)224 conn.close()225 if getattr(conn, 'auto_open', 1) == 0:226 # This is a proxied connection that has been mutated by227 # httplib._tunnel() and cannot be reused (since it would228 # attempt to bypass the proxy)229 conn = None230231 return conn or self._new_conn()232233 def _put_conn(self, conn):
11 unmodified lines
245 If the pool is closed, then the connection will be closed and discarded.246 """247 try:248 self.pool.put(conn, block=False)240 return # Everything is dandy, done.249 return # Everything is dandy, done.250 except AttributeError:251 # self.pool is None.252 pass253 except Full:
5 unmodified lines
259 # Connection never got put back into the pool, close it.260 if conn:261 conn.close()262263 def _validate_conn(self, conn):264 """265 Called right before a request is made, after the socket is created.266 """267 pass268269 def _get_timeout(self, timeout):270 """ Helper that always returns a :class:`urllib3.util.Timeout` """271 if timeout is _Default:272 return self.timeout.clone()
23 unmodified lines
296 """297 self.num_requests += 1298299 timeout_obj = self._get_timeout(timeout)300 timeout_obj.start_connect()301 conn.timeout = timeout_obj.connect_timeout302286 try:287 timeout_obj.start_connect()288 conn.timeout = timeout_obj.connect_timeout289 # conn.request() calls httplib.*.request, not the method in290 # urllib3.request. It also calls makefile (recv) on the socket.291 conn.request(method, url, **httplib_request_kw)292 except SocketTimeout:293 raise ConnectTimeoutError(294 self, "Connection to %s timed out. (connect timeout=%s)" %295 (self.host, timeout_obj.connect_timeout))303 # Trigger any extra validation we need to do.304 self._validate_conn(conn)305306 # conn.request() calls httplib.*.request, not the method in307 # urllib3.request. It also calls makefile (recv) on the socket.308 conn.request(method, url, **httplib_request_kw)309310 # Reset the timeout for the recv() on the socket311 read_timeout = timeout_obj.read_timeout312313 # App Engine doesn't have a sock attr301 if hasattr(conn, 'sock'):314 if getattr(conn, 'sock', None):315 # In Python 3 socket.py will catch EAGAIN and return None when you316 # try and read into the file pointer created by http.client, which317 # instead raises a BadStatusLine exception. Instead of catching318 # the exception and assuming all BadStatusLine exceptions are read319 # timeouts, check for a zero timeout before making the request.320 if read_timeout == 0:321 raise ReadTimeoutError(309 self, url,310 "Read timed out. (read timeout=%s)" % read_timeout)322 self, url, "Read timed out. (read timeout=%s)" % read_timeout)323 if read_timeout is Timeout.DEFAULT_TIMEOUT:324 conn.sock.settimeout(socket.getdefaulttimeout())313 else: # None or a value325 else: # None or a value326 conn.sock.settimeout(read_timeout)327328 # Receive the response from the server329 try:318 try: # Python 2.7+, use buffering of HTTP responses330 try: # Python 2.7+, use buffering of HTTP responses331 httplib_response = conn.getresponse(buffering=True)320 except TypeError: # Python 2.6 and older332 except TypeError: # Python 2.6 and older333 httplib_response = conn.getresponse()334 except SocketTimeout:335 raise ReadTimeoutError(336 self, url, "Read timed out. (read timeout=%s)" % read_timeout)
3 unmodified lines
340 # case, rethrow the original. We need to do this because of:341 # http://bugs.python.org/issue10272342 if 'timed out' in str(e) or \343 'did not complete (read)' in str(e): # Python 2.6332 raise ReadTimeoutError(self, url, "Read timed out.")344 raise ReadTimeoutError(345 self, url, "Read timed out. (read timeout=%s)" % read_timeout)346347 raise348336 except SocketError as e: # Platform-specific: Python 2349 except SocketError as e: # Platform-specific: Python 2350 # See the above comment about EAGAIN in Python 3. In Python 2 we351 # have to specifically catch it and throw the timeout error352 if e.errno in _blocking_errnos:353 raise ReadTimeoutError(341 self, url,342 "Read timed out. (read timeout=%s)" % read_timeout)354 self, url, "Read timed out. (read timeout=%s)" % read_timeout)355356 raise357358 # AppEngine doesn't have a version attr.
16 unmodified lines
375 if conn:376 conn.close()377378 except Empty:367 pass # Done.379 pass # Done.380381 def is_same_host(self, url):382 """383 Check if the given ``url`` is a member of the same host as this
12 unmodified lines
396 port = None397398 return (scheme, host, port) == (self.scheme, self.host, self.port)399388 def urlopen(self, method, url, body=None, headers=None, retries=3,400 def urlopen(self, method, url, body=None, headers=None, retries=None,401 redirect=True, assert_same_host=True, timeout=_Default,402 pool_timeout=None, release_conn=None, **response_kw):403 """404 Get a connection from the pool and perform an HTTP request. This is the
25 unmodified lines
430 If-None-Match, etc. If None, pool headers are used. If provided,431 these headers completely replace any pool-specific headers.432433 :param retries:422 Number of retries to allow before raising a MaxRetryError exception.423 If `False`, then retries are disabled and any exception is raised424 immediately.434 Configure the number of retries to allow before raising a435 :class:`~urllib3.exceptions.MaxRetryError` exception.436437 Pass ``None`` to retry until you receive a response. Pass a438 :class:`~urllib3.util.retry.Retry` object for fine-grained control439 over different types of retries.440 Pass an integer number to retry connection errors that many times,441 but no other types of errors. Pass zero to never retry.442443 If ``False``, then retries are disabled and any exception is raised444 immediately. Also, instead of raising a MaxRetryError on redirects,445 the redirect response will be returned.446447 :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.448449 :param redirect:450 If True, automatically handle redirects (status codes 301, 302,451 303, 307, 308). Each redirect counts as a retry. Disabling retries452 will disable redirect, too.
29 unmodified lines
482 """483 if headers is None:484 headers = self.headers485463 if retries < 0 and retries is not False:464 raise MaxRetryError(self, url)486 if not isinstance(retries, Retry):487 retries = Retry.from_int(retries, redirect=redirect, default=self.retries)488489 if release_conn is None:490 release_conn = response_kw.get('preload_content', True)491492 # Check host493 if assert_same_host and not self.is_same_host(url):471 raise HostChangedError(self, url, retries - 1)494 raise HostChangedError(self, url, retries)495496 conn = None497498 # Merge the proxy headers. Only do this in HTTP. We have to copy the
7 unmodified lines
506 # complains about UnboundLocalError.507 err = None508509 try:487 # Request a connection from the queue510 # Request a connection from the queue.511 conn = self._get_conn(timeout=pool_timeout)512490 # Make the request on the httplib connection object513 # Make the request on the httplib connection object.514 httplib_response = self._make_request(conn, method, url,515 timeout=timeout,516 body=body, headers=headers)517
30 unmodified lines
548 # be replaced during the next _get_conn() call.549 conn.close()550 conn = None551529 if not retries:530 if isinstance(e, TimeoutError):531 # TimeoutError is exempt from MaxRetryError-wrapping.532 # FIXME: ... Not sure why. Add a reason here.533 raise552 stacktrace = sys.exc_info()[2]553 if isinstance(e, SocketError) and self.proxy:554 e = ProxyError('Cannot connect to proxy.', e)555 elif isinstance(e, (SocketError, HTTPException)):556 e = ProtocolError('Connection aborted.', e)557535 # Wrap unexpected exceptions with the most appropriate536 # module-level exception and re-raise.537 if isinstance(e, SocketError) and self.proxy:538 raise ProxyError('Cannot connect to proxy.', e)558 retries = retries.increment(method, url, error=e,559 _pool=self, _stacktrace=stacktrace)560 retries.sleep()561540 if retries is False:541 raise ConnectionError('Connection failed.', e)542543 raise MaxRetryError(self, url, e)544562 # Keep track of the error for the retry warning.563 err = e564565 finally:
4 unmodified lines
570 self._put_conn(conn)571572 if not conn:573 # Try again557 log.warning("Retrying (%d attempts remain) after connection "574 log.warning("Retrying (%r) after connection "575 "broken by '%r': %s" % (retries, err, url))559 return self.urlopen(method, url, body, headers, retries - 1,576 return self.urlopen(method, url, body, headers, retries,577 redirect, assert_same_host,578 timeout=timeout, pool_timeout=pool_timeout,579 release_conn=release_conn, **response_kw)580581 # Handle redirect?582 redirect_location = redirect and response.get_redirect_location()566 if redirect_location and retries is not False:583 if redirect_location:584 if response.status == 303:585 method = 'GET'586587 try:588 retries = retries.increment(method, url, response=response, _pool=self)589 except MaxRetryError:590 if retries.raise_on_redirect:591 raise592 return response593594 log.info("Redirecting %s -> %s" % (url, redirect_location))595 return self.urlopen(method, redirect_location, body, headers,596 retries=retries, redirect=redirect,571 retries - 1, redirect, assert_same_host,572 timeout=timeout, pool_timeout=pool_timeout,573 release_conn=release_conn, **response_kw)597 assert_same_host=assert_same_host,598 timeout=timeout, pool_timeout=pool_timeout,599 release_conn=release_conn, **response_kw)600601 # Check if we should retry the HTTP response.602 if retries.is_forced_retry(method, status_code=response.status):603 retries = retries.increment(method, url, response=response, _pool=self)604 retries.sleep()605 log.info("Forced retry: %s" % url)606 return self.urlopen(method, url, body, headers,607 retries=retries, redirect=redirect,608 assert_same_host=assert_same_host,609 timeout=timeout, pool_timeout=pool_timeout,610 release_conn=release_conn, **response_kw)611612 return response613614615class HTTPSConnectionPool(HTTPConnectionPool):
17 unmodified lines
633 scheme = 'https'634 ConnectionCls = HTTPSConnection635636 def __init__(self, host, port=None,600 strict=False, timeout=None, maxsize=1,601 block=False, headers=None,637 strict=False, timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1,638 block=False, headers=None, retries=None,639 _proxy=None, _proxy_headers=None,640 key_file=None, cert_file=None, cert_reqs=None,641 ca_certs=None, ssl_version=None,642 assert_hostname=None, assert_fingerprint=None,643 **conn_kw):644608 if sys.version_info < (2, 7): # Python 2.6 or older609 conn_kw.pop('source_address', None)610645 HTTPConnectionPool.__init__(self, host, port, strict, timeout, maxsize,612 block, headers, _proxy, _proxy_headers, **conn_kw)646 block, headers, retries, _proxy, _proxy_headers,647 **conn_kw)648 self.key_file = key_file649 self.cert_file = cert_file650 self.cert_reqs = cert_reqs651 self.ca_certs = ca_certs652 self.ssl_version = ssl_version653 self.assert_hostname = assert_hostname654 self.assert_fingerprint = assert_fingerprint620 self.conn_kw = conn_kw655656 def _prepare_conn(self, conn):657 """658 Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
7 unmodified lines
666 ca_certs=self.ca_certs,667 assert_hostname=self.assert_hostname,668 assert_fingerprint=self.assert_fingerprint)669 conn.ssl_version = self.ssl_version636 conn.conn_kw = self.conn_kw670671 if self.proxy is not None:672 # Python 2.7+673 try:674 set_tunnel = conn.set_tunnel675 except AttributeError: # Platform-specific: Python 2.6676 set_tunnel = conn._set_tunnel677678 if sys.version_info <= (2, 6, 4) and not self.proxy_headers: # Python 2.6.4 and older679 set_tunnel(self.host, self.port)680 else:644 set_tunnel(self.host, self.port, self.proxy_headers)681 set_tunnel(self.host, self.port, self.proxy_headers)682683 # Establish tunnel connection early, because otherwise httplib684 # would improperly set Host: header to proxy's IP:port.685 conn.connect()686
17 unmodified lines
704 if self.proxy is not None:705 actual_host = self.proxy.host706 actual_port = self.proxy.port707670 extra_params = {}671 if not six.PY3: # Python 2672 extra_params['strict'] = self.strict673 extra_params.update(self.conn_kw)674708 conn = self.ConnectionCls(host=actual_host, port=actual_port,709 timeout=self.timeout.connect_timeout,677 **extra_params)678 if self.proxy is not None:679 # Enable Nagle's algorithm for proxies, to avoid packet680 # fragmentation.681 conn.tcp_nodelay = 0710 strict=self.strict, **self.conn_kw)711712 return self._prepare_conn(conn)713714 def _validate_conn(self, conn):715 """716 Called right before a request is made, after the socket is created.717 """718 super(HTTPSConnectionPool, self)._validate_conn(conn)719720 # Force connect early to allow us to validate the connection.721 if not conn.sock:722 conn.connect()723724 if not conn.is_verified:725 warnings.warn((726 'Unverified HTTPS request is being made. '727 'Adding certificate verification is strongly advised. See: '728 'https://urllib3.readthedocs.org/en/latest/security.html '729 '(This warning will only appear once by default.)'),730 InsecureRequestWarning)731732733def connection_from_url(url, **kw):734 """735 Given a url, return an :class:`.ConnectionPool` instance of its host.736
7 unmodified lines
744 Passes additional parameters to the constructor of the appropriate745 :class:`.ConnectionPool`. Useful for specifying things like746 timeout, maxsize, headers, etc.747701 Example: ::748 Example::749750 >>> conn = connection_from_url('http://google.com/')751 >>> r = conn.request('GET', '/')752 """
5 unmodified lines
modified:requests/packages/urllib3/exceptions.py+25 added-12 removed
1# urllib3/exceptions.py2# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php172## Base Exceptions34class HTTPError(Exception):5 "Base exception used by this module."6 pass78class HTTPWarning(Warning):9 "Base warning used by this module."10 pass11121314class PoolError(HTTPError):15 "Base exception for errors caused within a pool."16 def __init__(self, pool, message):17 self.pool = pool
24 unmodified lines
42 "Raised when the connection to a proxy fails."43 pass444547class ConnectionError(HTTPError):48 "Raised when a normal connection fails."46class DecodeError(HTTPError):47 "Raised when automatic decoding based on Content-Type fails."48 pass495052class DecodeError(HTTPError):53 "Raised when automatic decoding based on Content-Type fails."51class ProtocolError(HTTPError):52 "Raised when something unexpected happens mid-request/response."53 pass545556#: Renamed to ProtocolError but aliased for backwards compatibility.57ConnectionError = ProtocolError585960## Leaf Exceptions6162class MaxRetryError(RequestError):63 "Raised when the maximum number of retries is exceeded."
2 unmodified lines
66 self.reason = reason6768 message = "Max retries exceeded with url: %s" % url69 if reason:67 message += " (Caused by %s: %s)" % (type(reason), reason)70 message += " (Caused by %r)" % reason71 else:72 message += " (Caused by redirect)"7374 RequestError.__init__(self, pool, url, message)
43 unmodified lines
118 "Raised when a request enters a pool after the pool has been closed."119 pass120121119class LocationParseError(ValueError, HTTPError):122class LocationValueError(ValueError, HTTPError):123 "Raised when there is something wrong with a given URL input."124 pass125126127class LocationParseError(LocationValueError):128 "Raised when get_host or similar fails to parse the URL input."129130 def __init__(self, location):131 message = "Failed to parse: %s" % location132 HTTPError.__init__(self, message)133134 self.location = location135136137class InsecureRequestWarning(HTTPWarning):138 "Warned when making an unverified HTTPS request."139 pass
modified:requests/packages/urllib3/fields.py+13 added-13 removed
1# urllib3/fields.py2# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php61import email.utils2import mimetypes34from .packages import six
66 unmodified lines
71 def from_tuples(cls, fieldname, value):72 """73 A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.7481 Supports constructing :class:`~urllib3.fields.RequestField` from parameter82 of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type)83 tuple where the MIME type is optional. For example: ::75 Supports constructing :class:`~urllib3.fields.RequestField` from76 parameter of key/value strings AND key/filetuple. A filetuple is a77 (filename, data, MIME type) tuple where the MIME type is optional.78 For example::7980 'foo': 'bar',81 'fakefile': ('foofile.txt', 'contents of foofile'),82 'realfile': ('barfile.txt', open('realfile').read()),
36 unmodified lines
119 Useful for single headers that are composed of multiple items. E.g.,120 'Content-Disposition' fields.121122 :param header_parts:128 A sequence of (k, v) typles or a :class:`dict` of (k, v) to format as129 `k1="v1"; k2="v2"; ...`.123 A sequence of (k, v) typles or a :class:`dict` of (k, v) to format124 as `k1="v1"; k2="v2"; ...`.125 """126 parts = []127 iterable = header_parts128 if isinstance(header_parts, dict):
23 unmodified lines
152153 lines.append('\r\n')154 return '\r\n'.join(lines)155161 def make_multipart(self, content_disposition=None, content_type=None, content_location=None):156 def make_multipart(self, content_disposition=None, content_type=None,157 content_location=None):158 """159 Makes this request field into a multipart request field.160161 This method overrides "Content-Disposition", "Content-Type" and
5 unmodified lines
167 The 'Content-Location' of the request body.168169 """170 self.headers['Content-Disposition'] = content_disposition or 'form-data'175 self.headers['Content-Disposition'] += '; '.join(['', self._render_parts((('name', self._name), ('filename', self._filename)))])171 self.headers['Content-Disposition'] += '; '.join([172 '', self._render_parts(173 (('name', self._name), ('filename', self._filename))174 )175 ])176 self.headers['Content-Type'] = content_type177 self.headers['Content-Location'] = content_location
modified:requests/packages/urllib3/filepost.py+4 added-11 removed
1# urllib3/filepost.py2# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php61import codecs8import mimetypes23from uuid import uuid44from io import BytesIO5
24 unmodified lines
30 else:31 i = iter(fields)3233 for field in i:41 if isinstance(field, RequestField):42 yield field43 else:44 yield RequestField.from_tuples(*field)34 if isinstance(field, RequestField):35 yield field36 else:37 yield RequestField.from_tuples(*field)383940def iter_fields(fields):41 """
52 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+25 added-18 removed
1# urllib3/poolmanager.py2# Copyright 2008-2014 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php61import logging23try: # Python 34 from urllib.parse import urljoin
2 unmodified lines
78from ._collections import RecentlyUsedContainer9from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool10from .connectionpool import port_by_scheme11from .exceptions import LocationValueError12from .request import RequestMethods18from .util import parse_url13from .util.url import parse_url14from .util.retry import Retry151617__all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']18
25 unmodified lines
44 :param \**connection_pool_kw:45 Additional parameters are used to create fresh46 :class:`urllib3.connectionpool.ConnectionPool` instances.4752 Example: ::48 Example::4950 >>> manager = PoolManager(num_pools=2)51 >>> r = manager.request('GET', 'http://google.com/')52 >>> r = manager.request('GET', 'http://google.com/mail')
44 unmodified lines
97 If ``port`` isn't given, it will be derived from the ``scheme`` using98 ``urllib3.connectionpool.port_by_scheme``.99 """100105 scheme = scheme or 'http'101 if not host:102 raise LocationValueError("No host specified.")103104 scheme = scheme or 'http'105 port = port or port_by_scheme.get(scheme, 80)108106 pool_key = (scheme, host, port)107108 with self.pools.lock:109 # If the scheme, host, or port doesn't match existing open
4 unmodified lines
114115 # Make a fresh ConnectionPool of the desired type116 pool = self._new_pool(scheme, host, port)117 self.pools[pool_key] = pool118119 return pool120121 def connection_from_url(self, url):122 """
35 unmodified lines
158159 # Support relative URLs for redirecting.160 redirect_location = urljoin(url, redirect_location)161164 # RFC 2616, Section 10.3.4162 # RFC 7231, Section 6.4.4163 if response.status == 303:164 method = 'GET'165168 log.info("Redirecting %s -> %s" % (url, redirect_location))169 kw['retries'] = kw.get('retries', 3) - 1 # Persist retries countdown166 retries = kw.get('retries')167 if not isinstance(retries, Retry):168 retries = Retry.from_int(retries, redirect=redirect)169170 kw['retries'] = retries.increment(method, redirect_location)171 kw['redirect'] = redirect172173 log.info("Redirecting %s -> %s" % (url, redirect_location))174 return self.urlopen(method, redirect_location, **kw)175176177class ProxyManager(PoolManager):
32 unmodified lines
210 proxy = parse_url(proxy_url)211 if not proxy.port:212 port = port_by_scheme.get(proxy.scheme, 80)213 proxy = proxy._replace(port=port)214215 assert proxy.scheme in ("http", "https"), \216 'Not supported proxy scheme %s' % proxy.scheme217218 self.proxy = proxy219 self.proxy_headers = proxy_headers or {}213 assert self.proxy.scheme in ("http", "https"), \214 'Not supported proxy scheme %s' % self.proxy.scheme220221 connection_pool_kw['_proxy'] = self.proxy222 connection_pool_kw['_proxy_headers'] = self.proxy_headers223224 super(ProxyManager, self).__init__(225 num_pools, headers, **connection_pool_kw)226227 def connection_from_host(self, host, port=None, scheme='http'):
26 unmodified lines
254 if u.scheme == "http":255 # For proxied HTTPS requests, httplib sets the necessary headers256 # on the CONNECT to the proxy. For HTTP, we'll definitely257 # need to set 'Host' at the very least.251 kw['headers'] = self._set_proxy_headers(url, kw.get('headers',252 self.headers))258 headers = kw.get('headers', self.headers)259 kw['headers'] = self._set_proxy_headers(url, headers)260254 return super(ProxyManager, self).urlopen(method, url, redirect, **kw)261 return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)262263264def proxy_from_url(url, **kw):265 return ProxyManager(proxy_url=url, **kw)
modified:requests/packages/urllib3/request.py+19 added-25 removed
1# urllib3/request.py2# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php61try:2 from urllib.parse import urlencode3except ImportError:4 from urllib import urlencode
14 unmodified lines
19 decides which type of request field encoding to use.2021 Specifically,2229 :meth:`.request_encode_url` is for sending requests whose fields are encoded30 in the URL (such as GET, HEAD, DELETE).23 :meth:`.request_encode_url` is for sending requests whose fields are24 encoded in the URL (such as GET, HEAD, DELETE).2526 :meth:`.request_encode_body` is for sending requests whose fields are27 encoded in the *body* of the request using multipart or www-form-urlencoded28 (such as for POST, PUT, PATCH).
15 unmodified lines
44 self.headers = headers or {}4546 def urlopen(self, method, url, body=None, headers=None,47 encode_multipart=True, multipart_boundary=None,54 **kw): # Abstract48 **kw): # Abstract49 raise NotImplemented("Classes extending RequestMethods must implement "50 "their own ``urlopen`` method.")5152 def request(self, method, url, fields=None, headers=None, **urlopen_kw):
1 unmodified line
54 Make a request using :meth:`urlopen` with the appropriate encoding of55 ``fields`` based on the ``method`` used.5657 This is a convenience method that requires the least amount of manual64 effort. It can be used in most situations, while still having the option65 to drop down to more specific methods when necessary, such as58 effort. It can be used in most situations, while still having the59 option to drop down to more specific methods when necessary, such as60 :meth:`request_encode_url`, :meth:`request_encode_body`,61 or even the lowest level :meth:`urlopen`.62 """63 method = method.upper()6465 if method in self._encode_url_methods:66 return self.request_encode_url(method, url, fields=fields,73 headers=headers,74 **urlopen_kw)67 headers=headers,68 **urlopen_kw)69 else:70 return self.request_encode_body(method, url, fields=fields,77 headers=headers,78 **urlopen_kw)71 headers=headers,72 **urlopen_kw)7374 def request_encode_url(self, method, url, fields=None, **urlopen_kw):75 """76 Make a request using :meth:`urlopen` with the ``fields`` encoded in
10 unmodified lines
87 Make a request using :meth:`urlopen` with the ``fields`` encoded in88 the body. This is useful for request methods like POST, PUT, PATCH, etc.8990 When ``encode_multipart=True`` (default), then97 :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the98 payload with the appropriate content type. Otherwise91 :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode92 the payload with the appropriate content type. Otherwise93 :meth:`urllib.urlencode` is used with the94 'application/x-www-form-urlencoded' content type.9596 Multipart encoding must be used when posting files, and it's reasonably103 safe to use it in other times too. However, it may break request signing,104 such as with OAuth.97 safe to use it in other times too. However, it may break request98 signing, such as with OAuth.99100 Supports an optional ``fields`` parameter of key/value strings AND101 key/filetuple. A filetuple is a (filename, data, MIME type) tuple where108 the MIME type is optional. For example: ::102 the MIME type is optional. For example::103104 fields = {105 'foo': 'bar',106 'fakefile': ('foofile.txt', 'contents of foofile'),
5 unmodified lines
112113 When uploading a file, providing a filename (the first parameter of the114 tuple) is optional but recommended to best mimick behavior of browsers.115122 Note that if ``headers`` are supplied, the 'Content-Type' header will be123 overwritten because it depends on the dynamic random boundary string116 Note that if ``headers`` are supplied, the 'Content-Type' header will117 be overwritten because it depends on the dynamic random boundary string118 which is used to compose the body of the request. The random boundary119 string can be explicitly set with the ``multipart_boundary`` parameter.120 """121 if encode_multipart:128 body, content_type = encode_multipart_formdata(fields or {},129 boundary=multipart_boundary)122 body, content_type = encode_multipart_formdata(123 fields or {}, boundary=multipart_boundary)124 else:125 body, content_type = (urlencode(fields or {}),132 'application/x-www-form-urlencoded')126 'application/x-www-form-urlencoded')127128 if headers is None:129 headers = self.headers130
5 unmodified lines
modified:requests/packages/urllib3/response.py+47 added-35 removed
1# urllib3/response.py2# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php678import logging1import zlib2import io3from socket import timeout as SocketTimeout45from ._collections import HTTPHeaderDict13from .exceptions import DecodeError6from .exceptions import ProtocolError, DecodeError, ReadTimeoutError7from .packages.six import string_types as basestring, binary_type8from .connection import HTTPException, BaseSSLError15from .util import is_fp_closed9from .util.response import is_fp_closed101118log = logging.getLogger(__name__)122013class DeflateDecoder(object):1415 def __init__(self):16 self._first_try = True
65 unmodified lines
82 self.strict = strict83 self.decode_content = decode_content8485 self._decoder = None94 self._body = body if body and isinstance(body, basestring) else None86 self._body = None87 self._fp = None88 self._original_response = original_response89 self._fp_bytes_read = 09091 if body and isinstance(body, (basestring, binary_type)):92 self._body = body9394 self._pool = pool95 self._connection = connection9697 if hasattr(body, 'read'):
59 unmodified lines
157 is useful if you want the ``.data`` property to continue working158 after having ``.read()`` the file object. (Overridden if ``amt`` is159 set.)160 """166 # Note: content-encoding value should be case-insensitive, per RFC 2616167 # Section 3.5161 # Note: content-encoding value should be case-insensitive, per RFC 7230162 # Section 3.2163 content_encoding = self.headers.get('content-encoding', '').lower()164 if self._decoder is None:165 if content_encoding in self.CONTENT_DECODERS:166 self._decoder = _get_decoder(content_encoding)
5 unmodified lines
172173 flush_decoder = False174175 try:181 if amt is None:182 # cStringIO doesn't like amt=None183 data = self._fp.read()184 flush_decoder = True185 else:186 cache_content = False187 data = self._fp.read(amt)188 if amt != 0 and not data: # Platform-specific: Buggy versions of Python.189 # Close the connection when no data is returned190 #191 # This is redundant to what httplib/http.client _should_192 # already do. However, versions of python released before193 # December 15, 2012 (http://bugs.python.org/issue16298) do not194 # properly close the connection in all cases. There is no harm195 # in redundantly calling close.196 self._fp.close()176 try:177 if amt is None:178 # cStringIO doesn't like amt=None179 data = self._fp.read()180 flush_decoder = True181 else:182 cache_content = False183 data = self._fp.read(amt)184 if amt != 0 and not data: # Platform-specific: Buggy versions of Python.185 # Close the connection when no data is returned186 #187 # This is redundant to what httplib/http.client _should_188 # already do. However, versions of python released before189 # December 15, 2012 (http://bugs.python.org/issue16298) do190 # not properly close the connection in all cases. There is191 # no harm in redundantly calling close.192 self._fp.close()193 flush_decoder = True194195 except SocketTimeout:196 # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but197 # there is yet no clean way to get at it from this context.198 raise ReadTimeoutError(self._pool, None, 'Read timed out.')199200 except BaseSSLError as e:201 # FIXME: Is there a better way to differentiate between SSLErrors?202 if not 'read operation timed out' in str(e): # Defensive:203 # This shouldn't happen but just in case we're missing an edge204 # case, let's avoid swallowing SSL errors.205 raise206207 raise ReadTimeoutError(self._pool, None, 'Read timed out.')208209 except HTTPException as e:210 # This includes IncompleteRead.211 raise ProtocolError('Connection broken: %r' % e, e)212213 self._fp_bytes_read += len(data)214215 try:216 if decode_content and self._decoder:217 data = self._decoder.decompress(data)218 except (IOError, zlib.error) as e:219 raise DecodeError(220 "Received response with content-encoding: %s, but "207 "failed to decode it." % content_encoding,208 e)221 "failed to decode it." % content_encoding, e)222223 if flush_decoder and decode_content and self._decoder:224 buf = self._decoder.decompress(binary_type())225 data += buf + self._decoder.flush()
28 unmodified lines
254255 if data:256 yield data257245258 @classmethod259 def from_httplib(ResponseCls, r, **response_kw):260 """261 Given an :class:`httplib.HTTPResponse` instance ``r``, return a
46 unmodified lines
308 raise IOError("HTTPResponse has no file to get a fileno from")309 elif hasattr(self._fp, "fileno"):310 return self._fp.fileno()311 else:300 raise IOError("The file-like object this HTTPResponse is wrapped "312 raise IOError("The file-like object this HTTPResponse is wrapped "313 "around has no file descriptor")314315 def flush(self):316 if self._fp is not None and hasattr(self._fp, 'flush'):
4 unmodified lines
modified:requests/adapters.py+2 added-1 removed
9 unmodified lines
1011import socket1213from .models import Response14from .packages.urllib3 import Retry15from .packages.urllib3.poolmanager import PoolManager, proxy_from_url16from .packages.urllib3.response import HTTPResponse17from .packages.urllib3.util import Timeout as TimeoutSauce18from .compat import urlparse, basestring, urldefrag, unquote
321 unmodified lines
340 redirect=False,341 assert_same_host=False,342 preload_content=False,343 decode_content=False,343 retries=self.max_retries,344 retries=Retry(self.max_retries, read=False),345 timeout=timeout346 )347348 # Send the request.
58 unmodified lines