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
Provenance
- Commit
fe693c4- Tree
319437a- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
Kenneth Reitz <me@kennethreitz.org>- Parent 1
9575d6a- Parent 2
170d626
21 files changed+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.php6-1 """2 NTLM authenticating pool, contributed by erikcederstran3 4 Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10110 unmodified linesmodified:requests/packages/urllib3/contrib/pyopenssl.py+21 added-181 removed
52 unmodified lines53 from pyasn1.type import univ, constraint54 from socket import _fileobject, timeout55 import ssl56 import select57-from cStringIO import StringIO57 58 from .. import connection59 from .. import util60 92 unmodified lines153 154 return dns_name155 156 158-class fileobject(_fileobject):159-160- def _wait_for_sock(self):161- rd, wd, ed = select.select([self._sock], [], [],162- self._sock.gettimeout())163- if not rd:164- raise timeout()165-166-167- 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 rv200-201- 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()234-235- 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)268-269- 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()334-335-157 class WrappedSocket(object):158 '''API-compatibility wrapper for Python OpenSSL's Connection-class.'''159 339- 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_eofs164 165 def fileno(self):166 return self.socket.fileno()167 168 def makefile(self, mode, bufsize=-1):347- return fileobject(self.connection, mode, bufsize)169+ return _fileobject(self, mode, bufsize)170 171+ 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 data188+189 def settimeout(self, timeout):190 return self.socket.settimeout(timeout)191 192 def sendall(self, data):70 unmodified linesmodified: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/5-5 try:6 from thread import get_ident as _get_ident7 except ImportError:8 from dummy_thread import get_ident as _get_ident251 unmodified linesmodified: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.php6-1+# For backwards compatibility, provide imports that used to be here.2 from .connection import is_connection_dropped3 from .request import make_headers4 from .response import is_fp_closed5 from .ssl_ import (7 unmodified lines13 from .timeout import (14 current_time,15 Timeout,16 )17+18+from .retry import Retry19 from .url import (20 get_host,21 parse_url,22 split_first,2 unmodified linesmodified:requests/packages/urllib3/util/connection.py+55 added-3 removed
1-from socket import error as SocketError1+import socket2 try:3 from select import poll, POLLIN4 except ImportError: # `poll` doesn't exist on OSX and other platforms5 poll = False1 unmodified line7 from select import select8 except ImportError: # `select` doesn't exist on AppEngine.9 select = False10 11+12 def is_connection_dropped(conn): # Platform-specific13 """14 Returns True if the connection is dropped and should be closed.15 6 unmodified lines22 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 True27 28 if not poll:29 if not select: # Platform-specific: AppEngine30 return False31 32 try:33 return select([sock], [], [], 0.0)[0]33- except SocketError:34+ except socket.error:35 return True36 37 # This version is better on platforms that support it.38 p = poll()3 unmodified lines42 # Either data is buffered (bad), or the connection is dropped.43 return True44 45 46+# This function is copied from socket.py in the Python 2.7 standard47+# library test suite. Added to its signature is only `socket_options`.48+def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,49+ source_address=None, socket_options=None):50+ """Connect to *address* and return the socket object.51 52+ 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+ """61+62+ 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)69+70+ # 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)73+74+ 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 sock80+81+ except socket.error as _:82+ err = _83+ if sock is not None:84+ sock.close()85+86+ if err is not None:87+ raise err88+ else:89+ raise socket.error("getaddrinfo returns an empty list")90+91+92+def _set_socket_options(sock, options):93+ if options is None:94+ return95+96+ for opt in options:97+ sock.setsockopt(*opt)modified:requests/packages/urllib3/util/request.py+11 added-8 removed
1 from base64 import b64encode2 3-from ..packages import six3+from ..packages.six import b4 5-5 ACCEPT_ENCODING = 'gzip,deflate'6 7 8 def 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.12 13 :param keep_alive:16 unmodified lines30 :param proxy_basic_auth:31 Colon-separated username:password string for 'proxy-authorization: basic ...'32 auth header.33 35- Example: ::34+ :param disable_cache:35+ If ``True``, adds 'cache-control: no-cache' header.36 37+ Example::38+39 >>> 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 lines58 headers['connection'] = 'keep-alive'59 60 if basic_auth:61 headers['authorization'] = 'Basic ' + \60- b64encode(six.b(basic_auth)).decode('utf-8')62+ b64encode(b(basic_auth)).decode('utf-8')63 64 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')67 66- return headers68+ if disable_cache:69+ headers['cache-control'] = 'no-cache'70 68-71+ return headersadded:requests/packages/urllib3/util/retry.py+279 added
1+import time2+import logging3+4+from ..exceptions import (5+ ProtocolError,6+ ConnectTimeoutError,7+ ReadTimeoutError,8+ MaxRetryError,9+)10+from ..packages import six11+12+13+log = logging.getLogger(__name__)14+15+16+class Retry(object):17+ """ Retry configuration.18+19+ Each retry attempt will create a new Retry object with updated values, so20+ they can be safely reused.21+22+ Retries can be defined as a default for a pool::23+24+ retries = Retry(connect=5, read=2, redirect=5)25+ http = PoolManager(retries=retries)26+ response = http.request('GET', 'http://example.com/')27+28+ Or per-request (which overrides the default for the pool)::29+30+ response = http.request('GET', 'http://example.com/', retries=Retry(10))31+32+ Retries can be disabled by passing ``False``::33+34+ response = http.request('GET', 'http://example.com/', retries=False)35+36+ Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless37+ retries are disabled, in which case the causing exception will be raised.38+39+40+ :param int total:41+ Total number of retries to allow. Takes precedence over other counts.42+43+ 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.46+47+ Set to ``0`` to fail on the first retry.48+49+ Set to ``False`` to disable and imply ``raise_on_redirect=False``.50+51+ :param int connect:52+ How many connection-related errors to retry on.53+54+ 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.56+57+ Set to ``0`` to fail on the first retry of this type.58+59+ :param int read:60+ How many times to retry on read errors.61+62+ These errors are raised after the request was sent to the server, so the63+ request may have side-effects.64+65+ Set to ``0`` to fail on the first retry of this type.66+67+ :param int redirect:68+ How many redirects to perform. Limit this to avoid infinite redirect69+ loops.70+71+ A redirect is a HTTP response with a status code 301, 302, 303, 307 or72+ 308.73+74+ Set to ``0`` to fail on the first retry of this type.75+76+ Set to ``False`` to disable and imply ``raise_on_redirect=False``.77+78+ :param iterable method_whitelist:79+ Set of uppercased HTTP method verbs that we should retry on.80+81+ 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`.84+85+ :param iterable status_forcelist:86+ A set of HTTP status codes that we should force a retry on. 87+88+ By default, this is disabled with ``None``.89+90+ :param float backoff_factor:91+ A backoff factor to apply between attempts. urllib3 will sleep for::92+93+ {backoff factor} * (2 ^ ({number of total retries} - 1))94+95+ 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`.98+99+ By default, backoff is disabled (set to 0).100+101+ :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+ """105+106+ DEFAULT_METHOD_WHITELIST = frozenset([107+ 'HEAD', 'GET', 'PUT', 'DELETE', 'OPTIONS', 'TRACE'])108+109+ #: Maximum backoff time.110+ BACKOFF_MAX = 120111+112+ 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):115+116+ self.total = total117+ self.connect = connect118+ self.read = read119+120+ if redirect is False or total is False:121+ redirect = 0122+ raise_on_redirect = False123+124+ 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?130+131+ 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)143+144+ @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.DEFAULT149+150+ if isinstance(retries, Retry):151+ return retries152+153+ 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_retries157+158+ def get_backoff_time(self):159+ """ Formula for computing the current backoff160+161+ :rtype: float162+ """163+ if self._observed_errors <= 1:164+ return 0165+166+ backoff_value = self.backoff_factor * (2 ** (self._observed_errors - 1))167+ return min(self.BACKOFF_MAX, backoff_value)168+169+ def sleep(self):170+ """ Sleep between retry attempts using an exponential backoff.171+172+ 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)179+180+ 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)185+186+ 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))191+192+ 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 False197+198+ return self.status_forcelist and status_code in self.status_forcelist199+200+ 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 False207+208+ return min(retry_counts) < 0209+210+ 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.212+213+ :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.218+219+ :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)224+225+ total = self.total226+ if total is not None:227+ total -= 1228+229+ _observed_errors = self._observed_errors230+ connect = self.connect231+ read = self.read232+ redirect = self.redirect233+234+ 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 += 1241+242+ 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 += 1249+250+ elif response and response.get_redirect_location():251+ # Redirect retry?252+ if redirect is not None:253+ redirect -= 1254+255+ else:256+ # FIXME: Nothing changed, scenario doesn't make sense.257+ _observed_errors += 1258+259+ new_retry = self.new(260+ total=total,261+ connect=connect, read=read, redirect=redirect,262+ _observed_errors=_observed_errors)263+264+ if new_retry.is_exhausted():265+ raise MaxRetryError(_pool, url, error)266+267+ log.debug("Incremented Retry for (url='%s'): %r" % (url, new_retry))268+269+ return new_retry270+271+272+ 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)276+277+278+# For backwards compatibility (equivalent to pre-v1.9):279+Retry.DEFAULT = Retry(3)modified:requests/packages/urllib3/util/ssl_.py+2 added-3 removed
32 unmodified lines33 20: sha134 }35 36 fingerprint = fingerprint.replace(':', '').lower()37+ digest_length, odd = divmod(len(fingerprint), 2)38 38- digest_length, rest = divmod(len(fingerprint), 2)39-40- 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.')41 42 # We need encode() here for py32; works on py2 and p33.43 fingerprint_bytes = unhexlify(fingerprint.encode())89 unmodified linesmodified: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 user3 from socket import _GLOBAL_DEFAULT_TIMEOUT4 import time5 6 from ..exceptions import TimeoutStateError7 8+# A sentinel value to indicate that no timeout was specified by the user in9+# urllib310+_Default = object()11 12 def 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()17 18 14-_Default = object()15-# The default timeout to use for socket connections. This is the attribute used16-# by httplib to define the default timeout19+class Timeout(object):20+ """ Timeout configuration.21 22+ Timeouts can be defined as a default for a pool::23 19-class 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/')27 23- Example usage:28+ Or per-request (which overrides the default for the pool)::29 25- .. code-block:: python30+ response = http.request('GET', 'http://example.com/', timeout=Timeout(10))31 27- 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``::33 34+ no_timeout = Timeout(connect=None, read=None)35+ response = http.request('GET', 'http://example.com/, timeout=no_timeout)36+37+38+ :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.43+44+ Defaults to None.45+46+ :type total: integer, float, or None47+48 :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.py11 unmodified lines63 None will set an infinite timeout.64 65 :type read: integer, float, or None66 50- :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.55-56- Defaults to None.57-58- :type total: integer, float, or None59-67 .. note::68 69 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.71 72+ 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.76+77 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.85 86 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 lines100 def __str__(self):101 return '%s(connect=%r, read=%r, total=%r)' % (102 type(self).__name__, self._connect, self._read, self.total)103 97-104 @classmethod105 def _validate_timeout(cls, value, name):100- """ Check that a timeout attribute is valid106+ """ Check that a timeout attribute is valid.107 108 :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 lines128 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))135 136 return value3 unmodified lines140 """ Create a new Timeout from a legacy timeout value.141 142 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.146 141- :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 lines179 180 def get_connect_duration(self):181 """ Gets the time elapsed since the call to :meth:`start_connect`.182 177- :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 lines196 197 This will be a positive float or integer, the value None198 (never timeout), or the default system timeout.199 194- :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._connect14 unmodified lines219 time taken by the connect timeout. If the connection time has not been220 established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be221 raised.222 217- :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 linesmodified:requests/packages/urllib3/util/url.py+14 added-5 removed
1 unmodified line2 3 from ..exceptions import LocationParseError4 5 6-class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):6+url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']7+8+9+class 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 = ()15 13- 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)20 21 @property22 def hostname(self):23 """For backwards-compatibility with urlparse. We're nice like that."""23 unmodified lines47 delimiter. Return two split parts and the matched delimiter.48 49 If not found, then the first part is the full input string.50 46- Example: ::51+ Example::52 53 >>> split_first('foo/bar?baz', '?/=')54 ('foo', 'bar?baz', '/')55 >>> split_first('foo/bar?baz', '123')24 unmodified lines80 performed to parse incomplete urls. Fields not provided will be None.81 82 Partly backwards-compatible with :mod:`urlparse`.83 79- Example: ::84+ Example::85 86 >>> parse_url('http://google.com/mail/')87 Url(scheme='http', host='google.com', port=None, path='/', ...)88 >>> parse_url('google.com:80')6 unmodified lines95 # simplified for our needs and less annoying.96 # Additionally, this implementations does silly things to be optimal97 # on CPython.98 99+ if not url:100+ # Empty101+ return Url()102+103 scheme = None104 auth = None105 host = None106 port = None65 unmodified linesmodified: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.php6-1 """2 urllib3 - Thread-safe connection pooling and re-using.3 """4 11 unmodified lines16 from . import exceptions17 from .filepost import encode_multipart_formdata18 from .poolmanager import PoolManager, ProxyManager, proxy_from_url19 from .response import HTTPResponse26-from .util import make_headers, get_host, Timeout20+from .util.request import make_headers21+from .util.url import get_host22+from .util.timeout import Timeout23+from .util.retry import Retry24 25 26 # Set default logging handler to avoid "No handler found" warnings.27 import logging19 unmodified lines47 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 handler53 54 # ... Clean up.55 del NullHandler56+57+58+# Set security warning to only go off once by default.59+import warnings60+warnings.simplefilter('module', exceptions.InsecureRequestWarning)61+62+def 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.php6-1 from collections import Mapping, MutableMapping2 try:3 from threading import RLock4 except ImportError: # Platform-specific: No threads available104 unmodified lines109 110 A ``dict`` like container for storing HTTP Headers.111 112 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.115 116 Using ``__setitem__`` syntax overwrites fields that compare equal117 case-insensitively in order to maintain ``dict``'s api. For fields that82 unmodified linesmodified: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.php6-1 import sys2 import socket3 from socket import timeout as SocketTimeout4 11-try: # Python 35+try: # Python 36 from http.client import HTTPConnection as _HTTPConnection, HTTPException7 except ImportError:8 from httplib import HTTPConnection as _HTTPConnection, HTTPException9 10+11 class DummyConnection(object):12 "Used to detect a failed ConnectionCls import."13 pass14 20-try: # Compiled with SSL?21- ssl = None15+16+try: # Compiled with SSL?17 HTTPSConnection = DummyConnection18+ import ssl19+ BaseSSLError = ssl.SSLError20+except (ImportError, AttributeError): # Platform-specific: No SSL.21+ ssl = None22 23 class BaseSSLError(BaseException):24 pass25 27- try: # Python 328- from http.client import HTTPSConnection as _HTTPSConnection29- except ImportError:30- from httplib import HTTPSConnection as _HTTPSConnection26 32- import ssl33- BaseSSLError = ssl.SSLError34-35-except (ImportError, AttributeError): # Platform-specific: No SSL.36- pass37-27 from .exceptions import (28 ConnectTimeoutError,29 )30 from .packages.ssl_match_hostname import match_hostname31 from .packages import six43-from .util import (44- assert_fingerprint,32+33+from .util.ssl_ import (34 resolve_cert_reqs,35 resolve_ssl_version,36 ssl_wrap_socket,37+ assert_fingerprint,38 )39 40+from .util import connection41 42+43 port_by_scheme = {44 'http': 80,45 'https': 443,46 }2 unmodified lines49 class HTTPConnection(_HTTPConnection, object):50 """51 Based on httplib.HTTPConnection but provides an extra constructor52 backwards-compatibility layer between older and newer Pythons.53+54+ Additional keyword parameters are used to configure attributes of the connection.55+ Accepted parameters include:56+57+ - ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool`58+ - ``source_address``: Set the source address for the current connection.59+60+ .. note:: This is ignored for Python 2.6. It is only applied for 2.7 and 3.x61+62+ - ``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.65+66+ For example, if you wish to enable TCP Keep Alive in addition to the defaults,67+ you might pass::68+69+ HTTPConnection.default_socket_options + [70+ (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),71+ ]72+73+ Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).74 """75 76 default_port = port_by_scheme['http']77 65- # 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)]81 82+ #: Whether this connection verifies the host's certificate.83+ is_verified = False84+85 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)88 89 # Pre-set source_address in case we have an older Python like 2.6.90 self.source_address = kw.get('source_address')91 92+ 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)98+99+ #: 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)102+103 # Superclass also sets self.source_address in Python 2.7+.78- _HTTPConnection.__init__(self, *args, **kw) 104+ _HTTPConnection.__init__(self, *args, **kw)105 106 def _new_conn(self):107 """ Establish a socket connection and set nodelay settings on it.108 83- :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_address114 89- 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_options117 118+ try:119+ conn = connection.create_connection(120+ (self.host, self.port), self.timeout, **extra_kw)121+122+ except SocketTimeout:123+ raise ConnectTimeoutError(124+ self, "Connection to %s timed out. (connect timeout=%s)" %125+ (self.host, self.timeout))126+127 return conn128 129 def _prepare_conn(self, conn):130 self.sock = conn2 unmodified lines133 # 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 = 0139 140 def connect(self):141 conn = self._new_conn()142 self._prepare_conn(conn)28 unmodified lines171 """172 cert_reqs = None173 ca_certs = None174 ssl_version = None140- conn_kw = {}175 176 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 lines185 self.assert_fingerprint = assert_fingerprint186 187 def connect(self):188 # Add certificate verification189+ conn = self._new_conn()190 156- 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))164-165- sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY,166- self.tcp_nodelay)167-191 resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)192 resolved_ssl_version = resolve_ssl_version(self.ssl_version)193 194 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)198 176- 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 = 0205 206 # Override the host with the one we're requesting data from.207 hostname = self._tunnel_host208 209 # 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 lines221 elif self.assert_hostname is not False:222 match_hostname(self.sock.getpeercert(),223 self.assert_hostname or hostname)224 225+ self.is_verified = resolved_cert_reqs == ssl.CERT_REQUIRED226 227+228 if ssl:229 # Make a copy for testing.230 UnverifiedHTTPSConnection = HTTPSConnection231 HTTPSConnection = VerifiedHTTPSConnectionmodified: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.php6-7-import sys1 import errno2 import logging3+import sys4+import warnings5 6 from socket import error as SocketError, timeout as SocketTimeout7 import socket8 14-try: # Python 39+try: # Python 310 from queue import LifoQueue, Empty, Full11 except ImportError:12 from Queue import LifoQueue, Empty, Full13 import Queue as _ # Platform-specific: Windows14 15 16 from .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 )29 from .packages.ssl_match_hostname import CertificateError30 from .packages import six31 from .connection import (3 unmodified lines35 HTTPException, BaseSSLError,36 )37 from .request import RequestMethods38 from .response import HTTPResponse44-from .util import (45- get_host,46- is_connection_dropped,47- Timeout,48-)39 40+from .util.connection import is_connection_dropped41+from .util.retry import Retry42+from .util.timeout import Timeout43+from .util.url import get_host44 45+46 xrange = six.moves.xrange47 48 log = logging.getLogger(__name__)49 50 _Default = object()51 57-## Pool objects52 53+## Pool objects54 class ConnectionPool(object):55 """56 Base class for all connection pools, such as57 :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.2 unmodified lines60 scheme = None61 QueueCls = LifoQueue62 63 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.")66 67 # httplib doesn't like it when we include brackets in ipv6 addresses73- host = host.strip('[]')74-75- self.host = host68+ self.host = host.strip('[]')69 self.port = port70 71 def __str__(self):72 return '%s(host=%r, port=%r)' % (type(self).__name__,1 unmodified line74 75 # This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l25276 _blocking_errnos = set([errno.EAGAIN, errno.EWOULDBLOCK])77 78+79 class HTTPConnectionPool(ConnectionPool, RequestMethods):80 """81 Thread-safe connection pool for one host.82 36 unmodified lines119 :param headers:120 Headers to include with all requests, unless other headers are given121 explicitly.122 123+ :param retries:124+ Retry configuration to use by default with requests in this pool.125+126 :param _proxy:127 Parsed proxy URL, should not be used directly, instead, see128 :class:`urllib3.connectionpool.ProxyManager`"129 130 :param _proxy_headers:131 A dictionary with proxy headers, should not be used directly,132 instead, see :class:`urllib3.connectionpool.ProxyManager`"133+134+ :param \**conn_kw:135+ Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,136+ :class:`urllib3.connection.HTTPSConnection` instances.137 """138 139 scheme = 'http'140 ConnectionCls = HTTPConnection141 142 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)149 150 self.strict = strict151 149- # 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)154 155+ if retries is None:156+ retries = Retry.DEFAULT157+158 self.timeout = timeout159+ self.retries = retries160 161 self.pool = self.QueueCls(maxsize)162 self.block = block163 6 unmodified lines170 171 # These are mostly for testing and debugging purposes.172 self.num_connections = 0173 self.num_requests = 0169-170- if sys.version_info < (2, 7): # Python 2.6 and older171- conn_kw.pop('source_address', None)174 self.conn_kw = conn_kw175 176+ 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', [])181+182 def _new_conn(self):183 """184 Return a fresh :class:`HTTPConnection`.185 """3 unmodified lines189 190 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 conn194 195 def _get_conn(self, timeout=None):196 """10 unmodified lines207 conn = None208 try:209 conn = self.pool.get(block=self.block, timeout=timeout)210 207- except AttributeError: # self.pool is None211+ except AttributeError: # self.pool is None212 raise ClosedPoolError(self, "Pool is closed.")213 214 except Empty:215 if self.block:5 unmodified lines221 # 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 = None230 231 return conn or self._new_conn()232 233 def _put_conn(self, conn):11 unmodified lines245 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 lines259 # Connection never got put back into the pool, close it.260 if conn:261 conn.close()262 263+ def _validate_conn(self, conn):264+ """265+ Called right before a request is made, after the socket is created.266+ """267+ pass268+269 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 lines296 """297 self.num_requests += 1298 299 timeout_obj = self._get_timeout(timeout)300+ timeout_obj.start_connect()301+ conn.timeout = timeout_obj.connect_timeout302 286- 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)305 306+ # 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)309+310 # Reset the timeout for the recv() on the socket311 read_timeout = timeout_obj.read_timeout312 313 # 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)327 328 # 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 lines340 # 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)346 347 raise348 336- 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)355 356 raise357 358 # AppEngine doesn't have a version attr.16 unmodified lines375 if conn:376 conn.close()377 378 except Empty:367- pass # Done.379+ pass # Done.380 381 def is_same_host(self, url):382 """383 Check if the given ``url`` is a member of the same host as this12 unmodified lines396 port = None397 398 return (scheme, host, port) == (self.scheme, self.host, self.port)399 388- 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 the25 unmodified lines430 If-None-Match, etc. If None, pool headers are used. If provided,431 these headers completely replace any pool-specific headers.432 433 :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.436 437+ 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.442+443+ 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.446+447+ :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.448+449 :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 lines482 """483 if headers is None:484 headers = self.headers485 463- 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)488 489 if release_conn is None:490 release_conn = response_kw.get('preload_content', True)491 492 # 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)495 496 conn = None497 498 # Merge the proxy headers. Only do this in HTTP. We have to copy the7 unmodified lines506 # complains about UnboundLocalError.507 err = None508 509 try:487- # Request a connection from the queue510+ # Request a connection from the queue.511 conn = self._get_conn(timeout=pool_timeout)512 490- # 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 lines548 # be replaced during the next _get_conn() call.549 conn.close()550 conn = None551 529- 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)557 535- # 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()561 540- if retries is False:541- raise ConnectionError('Connection failed.', e)542-543- raise MaxRetryError(self, url, e)544-562 # Keep track of the error for the retry warning.563 err = e564 565 finally:4 unmodified lines570 self._put_conn(conn)571 572 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)580 581 # 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'586+587+ try:588+ retries = retries.increment(method, url, response=response, _pool=self)589+ except MaxRetryError:590+ if retries.raise_on_redirect:591+ raise592+ return response593+594 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)600 601+ # 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)611+612 return response613 614 615 class HTTPSConnectionPool(HTTPConnectionPool):17 unmodified lines633 scheme = 'https'634 ConnectionCls = HTTPSConnection635 636 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):644 608- if sys.version_info < (2, 7): # Python 2.6 or older609- conn_kw.pop('source_address', None)610-645 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_kw655 656 def _prepare_conn(self, conn):657 """658 Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`7 unmodified lines666 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_kw670 671 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_tunnel677+678+ 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)682+683 # Establish tunnel connection early, because otherwise httplib684 # would improperly set Host: header to proxy's IP:port.685 conn.connect()686 17 unmodified lines704 if self.proxy is not None:705 actual_host = self.proxy.host706 actual_port = self.proxy.port707 670- extra_params = {}671- if not six.PY3: # Python 2672- extra_params['strict'] = self.strict673- extra_params.update(self.conn_kw)674-708 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)711 712 return self._prepare_conn(conn)713 714+ 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)719 720+ # Force connect early to allow us to validate the connection.721+ if not conn.sock:722+ conn.connect()723+724+ 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)731+732+733 def connection_from_url(url, **kw):734 """735 Given a url, return an :class:`.ConnectionPool` instance of its host.736 7 unmodified lines744 Passes additional parameters to the constructor of the appropriate745 :class:`.ConnectionPool`. Useful for specifying things like746 timeout, maxsize, headers, etc.747 701- Example: ::748+ Example::749 750 >>> conn = connection_from_url('http://google.com/')751 >>> r = conn.request('GET', '/')752 """5 unmodified linesmodified: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.php1 7-2 ## Base Exceptions3 4 class HTTPError(Exception):5 "Base exception used by this module."6 pass7 8+class HTTPWarning(Warning):9+ "Base warning used by this module."10+ pass11 12+13+14 class PoolError(HTTPError):15 "Base exception for errors caused within a pool."16 def __init__(self, pool, message):17 self.pool = pool24 unmodified lines42 "Raised when the connection to a proxy fails."43 pass44 45 47-class ConnectionError(HTTPError):48- "Raised when a normal connection fails."46+class DecodeError(HTTPError):47+ "Raised when automatic decoding based on Content-Type fails."48 pass49 50 52-class DecodeError(HTTPError):53- "Raised when automatic decoding based on Content-Type fails."51+class ProtocolError(HTTPError):52+ "Raised when something unexpected happens mid-request/response."53 pass54 55 56+#: Renamed to ProtocolError but aliased for backwards compatibility.57+ConnectionError = ProtocolError58+59+60 ## Leaf Exceptions61 62 class MaxRetryError(RequestError):63 "Raised when the maximum number of retries is exceeded."2 unmodified lines66 self.reason = reason67 68 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)"73 74 RequestError.__init__(self, pool, url, message)43 unmodified lines118 "Raised when a request enters a pool after the pool has been closed."119 pass120 121 119-class LocationParseError(ValueError, HTTPError):122+class LocationValueError(ValueError, HTTPError):123+ "Raised when there is something wrong with a given URL input."124+ pass125+126+127+class LocationParseError(LocationValueError):128 "Raised when get_host or similar fails to parse the URL input."129 130 def __init__(self, location):131 message = "Failed to parse: %s" % location132 HTTPError.__init__(self, message)133 134 self.location = location135+136+137+class InsecureRequestWarning(HTTPWarning):138+ "Warned when making an unverified HTTPS request."139+ passmodified: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.php6-1 import email.utils2 import mimetypes3 4 from .packages import six66 unmodified lines71 def from_tuples(cls, fieldname, value):72 """73 A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.74 81- 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::79 80 'foo': 'bar',81 'fakefile': ('foofile.txt', 'contents of foofile'),82 'realfile': ('barfile.txt', open('realfile').read()),36 unmodified lines119 Useful for single headers that are composed of multiple items. E.g.,120 'Content-Disposition' fields.121 122 :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 lines152 153 lines.append('\r\n')154 return '\r\n'.join(lines)155 161- 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.160 161 This method overrides "Content-Disposition", "Content-Type" and5 unmodified lines167 The 'Content-Location' of the request body.168 169 """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_locationmodified: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.php6-1 import codecs8-import mimetypes2 3 from uuid import uuid44 from io import BytesIO5 24 unmodified lines30 else:31 i = iter(fields)32 33 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)38 39 40 def iter_fields(fields):41 """52 unmodified linesmodified: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.php6-1 import logging2 3 try: # Python 34 from urllib.parse import urljoin2 unmodified lines7 8 from ._collections import RecentlyUsedContainer9 from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool10 from .connectionpool import port_by_scheme11+from .exceptions import LocationValueError12 from .request import RequestMethods18-from .util import parse_url13+from .util.url import parse_url14+from .util.retry import Retry15 16 17 __all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']18 25 unmodified lines44 :param \**connection_pool_kw:45 Additional parameters are used to create fresh46 :class:`urllib3.connectionpool.ConnectionPool` instances.47 52- Example: ::48+ Example::49 50 >>> manager = PoolManager(num_pools=2)51 >>> r = manager.request('GET', 'http://google.com/')52 >>> r = manager.request('GET', 'http://google.com/mail')44 unmodified lines97 If ``port`` isn't given, it will be derived from the ``scheme`` using98 ``urllib3.connectionpool.port_by_scheme``.99 """100 105- scheme = scheme or 'http'101+ if not host:102+ raise LocationValueError("No host specified.")103 104+ scheme = scheme or 'http'105 port = port or port_by_scheme.get(scheme, 80)108-106 pool_key = (scheme, host, port)107 108 with self.pools.lock:109 # If the scheme, host, or port doesn't match existing open4 unmodified lines114 115 # Make a fresh ConnectionPool of the desired type116 pool = self._new_pool(scheme, host, port)117 self.pools[pool_key] = pool118+119 return pool120 121 def connection_from_url(self, url):122 """35 unmodified lines158 159 # Support relative URLs for redirecting.160 redirect_location = urljoin(url, redirect_location)161 164- # RFC 2616, Section 10.3.4162+ # RFC 7231, Section 6.4.4163 if response.status == 303:164 method = 'GET'165 168- 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)169+170+ kw['retries'] = retries.increment(method, redirect_location)171 kw['redirect'] = redirect172+173+ log.info("Redirecting %s -> %s" % (url, redirect_location))174 return self.urlopen(method, redirect_location, **kw)175 176 177 class ProxyManager(PoolManager):32 unmodified lines210 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)214+215+ assert proxy.scheme in ("http", "https"), \216+ 'Not supported proxy scheme %s' % proxy.scheme217+218 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.scheme220+221 connection_pool_kw['_proxy'] = self.proxy222 connection_pool_kw['_proxy_headers'] = self.proxy_headers223+224 super(ProxyManager, self).__init__(225 num_pools, headers, **connection_pool_kw)226 227 def connection_from_host(self, host, port=None, scheme='http'):26 unmodified lines254 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)260 254- return super(ProxyManager, self).urlopen(method, url, redirect, **kw)261+ return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)262 263 264 def 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.php6-1 try:2 from urllib.parse import urlencode3 except ImportError:4 from urllib import urlencode14 unmodified lines19 decides which type of request field encoding to use.20 21 Specifically,22 29- :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).25 26 :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 lines44 self.headers = headers or {}45 46 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.")51 52 def request(self, method, url, fields=None, headers=None, **urlopen_kw):1 unmodified line54 Make a request using :meth:`urlopen` with the appropriate encoding of55 ``fields`` based on the ``method`` used.56 57 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()64 65 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)73 74 def request_encode_url(self, method, url, fields=None, **urlopen_kw):75 """76 Make a request using :meth:`urlopen` with the ``fields`` encoded in10 unmodified lines87 Make a request using :meth:`urlopen` with the ``fields`` encoded in88 the body. This is useful for request methods like POST, PUT, PATCH, etc.89 90 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.95 96 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.99 100 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::103 104 fields = {105 'foo': 'bar',106 'fakefile': ('foofile.txt', 'contents of foofile'),5 unmodified lines112 113 When uploading a file, providing a filename (the first parameter of the114 tuple) is optional but recommended to best mimick behavior of browsers.115 122- 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')127 128 if headers is None:129 headers = self.headers130 5 unmodified linesmodified: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.php6-7-8-import logging1 import zlib2 import io3+from socket import timeout as SocketTimeout4 5 from ._collections import HTTPHeaderDict13-from .exceptions import DecodeError6+from .exceptions import ProtocolError, DecodeError, ReadTimeoutError7 from .packages.six import string_types as basestring, binary_type8+from .connection import HTTPException, BaseSSLError15-from .util import is_fp_closed9+from .util.response import is_fp_closed10 11 18-log = logging.getLogger(__name__)12 20-13 class DeflateDecoder(object):14 15 def __init__(self):16 self._first_try = True65 unmodified lines82 self.strict = strict83 self.decode_content = decode_content84 85 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 = 090 91+ if body and isinstance(body, (basestring, binary_type)):92+ self._body = body93+94 self._pool = pool95 self._connection = connection96 97 if hasattr(body, 'read'):59 unmodified lines157 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 lines172 173 flush_decoder = False174 175 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 = True194 195+ 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.')199+200+ 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+ raise206+207+ raise ReadTimeoutError(self._pool, None, 'Read timed out.')208+209+ except HTTPException as e:210+ # This includes IncompleteRead.211+ raise ProtocolError('Connection broken: %r' % e, e)212+213 self._fp_bytes_read += len(data)214 215 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)222 223 if flush_decoder and decode_content and self._decoder:224 buf = self._decoder.decompress(binary_type())225 data += buf + self._decoder.flush()28 unmodified lines254 255 if data:256 yield data257 245-258 @classmethod259 def from_httplib(ResponseCls, r, **response_kw):260 """261 Given an :class:`httplib.HTTPResponse` instance ``r``, return a46 unmodified lines308 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")314 315 def flush(self):316 if self._fp is not None and hasattr(self._fp, 'flush'):4 unmodified linesmodified:requests/adapters.py+2 added-1 removed
9 unmodified lines10 11 import socket12 13 from .models import Response14+from .packages.urllib3 import Retry15 from .packages.urllib3.poolmanager import PoolManager, proxy_from_url16 from .packages.urllib3.response import HTTPResponse17 from .packages.urllib3.util import Timeout as TimeoutSauce18 from .compat import urlparse, basestring, urldefrag, unquote321 unmodified lines340 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 )347 348 # Send the request.58 unmodified lines