Skip to content
Myr

Update to urllib3 1.14

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

authored by Cory Benfield · committed by Cory Benfield · parent cbb0830 · Browse files · 10 files+228 added−37 removed
This commit

State

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

Diff stats

10 files+228 added−37 removed

  • other:+228 added−37 removed

10 files+228 added−37 removed

modified:requests/packages/urllib3/contrib/appengine.py+10 added-2 removed
142 unmodified lines
143 # Check if we should retry the HTTP response.144 if retries.is_forced_retry(method, status_code=http_response.status):145 retries = retries.increment(146 method, url, response=http_response, _pool=self)147 log.info("Forced retry: %s" % url)147 log.info("Forced retry: %s", url)148 retries.sleep()149 return self.urlopen(150 method, url,151 body=body, headers=headers,
11 unmodified lines
163164 if content_encoding == 'deflate':165 del urlfetch_resp.headers['content-encoding']166167 transfer_encoding = urlfetch_resp.headers.get('transfer-encoding')168 # We have a full response's content,169 # so let's make sure we don't report ourselves as chunked data.170 if transfer_encoding == 'chunked':171 encodings = transfer_encoding.split(",")172 encodings.remove('chunked')173 urlfetch_resp.headers['transfer-encoding'] = ','.join(encodings)174175 return HTTPResponse(176 # In order for decoding to work, we must present the content as177 # a file-like object.178 body=BytesIO(urlfetch_resp.content),
5 unmodified lines
184 def _get_absolute_timeout(self, timeout):185 if timeout is Timeout.DEFAULT_TIMEOUT:186 return 5 # 5s is the default timeout for URLFetch.187 if isinstance(timeout, Timeout):180 if timeout.read is not timeout.connect:188 if timeout._read is not timeout._connect:189 warnings.warn(190 "URLFetch does not support granular timeout settings, "191 "reverting to total timeout.", AppEnginePlatformWarning)192 return timeout.total
39 unmodified lines
modified:requests/packages/urllib3/contrib/ntlmpool.py+10 added-10 removed
41 unmodified lines
42 def _new_conn(self):43 # Performs the NTLM handshake that secures the connection. The socket44 # must be kept open while requests are performed.45 self.num_connections += 146 log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s' %47 (self.num_connections, self.host, self.authurl))46 log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s',47 self.num_connections, self.host, self.authurl)4849 headers = {}50 headers['Connection'] = 'Keep-Alive'51 req_header = 'Authorization'
3 unmodified lines
5556 # Send negotiation message57 headers[req_header] = (58 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))59 log.debug('Request headers: %s' % headers)59 log.debug('Request headers: %s', headers)60 conn.request('GET', self.authurl, None, headers)61 res = conn.getresponse()62 reshdr = dict(res.getheaders())63 log.debug('Response status: %s %s' % (res.status, res.reason))64 log.debug('Response headers: %s' % reshdr)65 log.debug('Response data: %s [...]' % res.read(100))63 log.debug('Response status: %s %s', res.status, res.reason)64 log.debug('Response headers: %s', reshdr)65 log.debug('Response data: %s [...]', res.read(100))6667 # Remove the reference to the socket, so that it can not be closed by68 # the response object (we want to keep the socket open)69 res.fp = None
16 unmodified lines
86 self.domain,87 self.pw,88 NegotiateFlags)89 headers[req_header] = 'NTLM %s' % auth_msg90 log.debug('Request headers: %s' % headers)90 log.debug('Request headers: %s', headers)91 conn.request('GET', self.authurl, None, headers)92 res = conn.getresponse()93 log.debug('Response status: %s %s' % (res.status, res.reason))94 log.debug('Response headers: %s' % dict(res.getheaders()))95 log.debug('Response data: %s [...]' % res.read()[:100])93 log.debug('Response status: %s %s', res.status, res.reason)94 log.debug('Response headers: %s', dict(res.getheaders()))95 log.debug('Response data: %s [...]', res.read()[:100])96 if res.status != 200:97 if res.status == 401:98 raise Exception('Server rejected request: wrong '99 'username or password')
16 unmodified lines
added:requests/packages/urllib3/contrib/socks.py+172 added
1# -*- coding: utf-8 -*-2"""3SOCKS support for urllib34~~~~~~~~~~~~~~~~~~~~~~~~~56This contrib module contains provisional support for SOCKS proxies from within7urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and8SOCKS5. To enable its functionality, either install PySocks or install this9module with the ``socks`` extra.1011Known Limitations:1213- Currently PySocks does not support contacting remote websites via literal14 IPv6 addresses. Any such connection attempt will fail.15- Currently PySocks does not support IPv6 connections to the SOCKS proxy. Any16 such connection attempt will fail.17"""18from __future__ import absolute_import1920try:21 import socks22except ImportError:23 import warnings24 from urllib3.exceptions import DependencyWarning2526 warnings.warn((27 'SOCKS support in urllib3 requires the installation of optional '28 'dependencies: specifically, PySocks. For more information, see '29 'https://urllib3.readthedocs.org/en/latest/contrib.html#socks-proxies'30 ),31 DependencyWarning32 )33 raise3435from socket import error as SocketError, timeout as SocketTimeout3637from urllib3.connection import (38 HTTPConnection, HTTPSConnection39)40from urllib3.connectionpool import (41 HTTPConnectionPool, HTTPSConnectionPool42)43from urllib3.exceptions import ConnectTimeoutError, NewConnectionError44from urllib3.poolmanager import PoolManager45from urllib3.util.url import parse_url4647try:48 import ssl49except ImportError:50 ssl = None515253class SOCKSConnection(HTTPConnection):54 """55 A plain-text HTTP connection that connects via a SOCKS proxy.56 """57 def __init__(self, *args, **kwargs):58 self._socks_options = kwargs.pop('_socks_options')59 super(SOCKSConnection, self).__init__(*args, **kwargs)6061 def _new_conn(self):62 """63 Establish a new connection via the SOCKS proxy.64 """65 extra_kw = {}66 if self.source_address:67 extra_kw['source_address'] = self.source_address6869 if self.socket_options:70 extra_kw['socket_options'] = self.socket_options7172 try:73 conn = socks.create_connection(74 (self.host, self.port),75 proxy_type=self._socks_options['socks_version'],76 proxy_addr=self._socks_options['proxy_host'],77 proxy_port=self._socks_options['proxy_port'],78 proxy_username=self._socks_options['username'],79 proxy_password=self._socks_options['password'],80 timeout=self.timeout,81 **extra_kw82 )8384 except SocketTimeout as e:85 raise ConnectTimeoutError(86 self, "Connection to %s timed out. (connect timeout=%s)" %87 (self.host, self.timeout))8889 except socks.ProxyError as e:90 # This is fragile as hell, but it seems to be the only way to raise91 # useful errors here.92 if e.socket_err:93 error = e.socket_err94 if isinstance(error, SocketTimeout):95 raise ConnectTimeoutError(96 self,97 "Connection to %s timed out. (connect timeout=%s)" %98 (self.host, self.timeout)99 )100 else:101 raise NewConnectionError(102 self,103 "Failed to establish a new connection: %s" % error104 )105 else:106 raise NewConnectionError(107 self,108 "Failed to establish a new connection: %s" % e109 )110111 except SocketError as e: # Defensive: PySocks should catch all these.112 raise NewConnectionError(113 self, "Failed to establish a new connection: %s" % e)114115 return conn116117118# We don't need to duplicate the Verified/Unverified distinction from119# urllib3/connection.py here because the HTTPSConnection will already have been120# correctly set to either the Verified or Unverified form by that module. This121# means the SOCKSHTTPSConnection will automatically be the correct type.122class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection):123 pass124125126class SOCKSHTTPConnectionPool(HTTPConnectionPool):127 ConnectionCls = SOCKSConnection128129130class SOCKSHTTPSConnectionPool(HTTPSConnectionPool):131 ConnectionCls = SOCKSHTTPSConnection132133134class SOCKSProxyManager(PoolManager):135 """136 A version of the urllib3 ProxyManager that routes connections via the137 defined SOCKS proxy.138 """139 pool_classes_by_scheme = {140 'http': SOCKSHTTPConnectionPool,141 'https': SOCKSHTTPSConnectionPool,142 }143144 def __init__(self, proxy_url, username=None, password=None,145 num_pools=10, headers=None, **connection_pool_kw):146 parsed = parse_url(proxy_url)147148 if parsed.scheme == 'socks5':149 socks_version = socks.PROXY_TYPE_SOCKS5150 elif parsed.scheme == 'socks4':151 socks_version = socks.PROXY_TYPE_SOCKS4152 else:153 raise ValueError(154 "Unable to determine SOCKS version from %s" % proxy_url155 )156157 self.proxy_url = proxy_url158159 socks_options = {160 'socks_version': socks_version,161 'proxy_host': parsed.host,162 'proxy_port': parsed.port,163 'username': username,164 'password': password,165 }166 connection_pool_kw['_socks_options'] = socks_options167168 super(SOCKSProxyManager, self).__init__(169 num_pools, headers, **connection_pool_kw170 )171172 self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme
modified:requests/packages/urllib3/util/response.py+1 added-1 removed
59 unmodified lines
606162def is_response_to_head(response):63 """64 Checks, wether a the request of a response has been a HEAD-request.64 Checks whether the request of a response has been a HEAD-request.65 Handles the quirks of AppEngine.6667 :param conn:68 :type conn: :class:`httplib.HTTPResponse`
6 unmodified lines
modified:requests/packages/urllib3/util/retry.py+2 added-2 removed
151 unmodified lines
152 return retries153154 redirect = bool(redirect) and None155 new_retries = cls(retries, redirect=redirect)156 log.debug("Converted retries value: %r -> %r" % (retries, new_retries))156 log.debug("Converted retries value: %r -> %r", retries, new_retries)157 return new_retries158159 def get_backoff_time(self):160 """ Formula for computing the current backoff
110 unmodified lines
271272 if new_retry.is_exhausted():273 raise MaxRetryError(_pool, url, error or ResponseError(cause))274275 log.debug("Incremented Retry for (url='%s'): %r" % (url, new_retry))275 log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)276277 return new_retry278279 def __repr__(self):
7 unmodified lines
modified:requests/packages/urllib3/util/ssl_.py+2 added-1 removed
108 unmodified lines
109 '2.7, 3.2, or later if you need this functionality.'110 )111 self.ciphers = cipher_suite112113 def wrap_socket(self, socket, server_hostname=None):113 def wrap_socket(self, socket, server_hostname=None, server_side=False):114 warnings.warn(115 'A true SSLContext object is not available. This prevents '116 'urllib3 from configuring SSL appropriately and may cause '117 'certain SSL connections to fail. For more information, see '
6 unmodified lines
124 'certfile': self.certfile,125 'ca_certs': self.ca_certs,126 'cert_reqs': self.verify_mode,127 'ssl_version': self.protocol,128 'server_side': server_side,129 }130 if self.supports_set_ciphers: # Platform-specific: Python 2.7+131 return wrap_socket(socket, ciphers=self.ciphers, **kwargs)132 else: # Platform-specific: Python 2.6
186 unmodified lines
modified:requests/packages/urllib3/__init__.py+2 added-2 removed
30 unmodified lines
31 pass3233__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'34__license__ = 'MIT'35__version__ = '1.13.1'35__version__ = '1.14'3637__all__ = (38 'HTTPConnectionPool',39 'HTTPSConnectionPool',
27 unmodified lines
67 handler = logging.StreamHandler()68 handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))69 logger.addHandler(handler)70 logger.setLevel(level)71 logger.debug('Added a stderr logging handler to logger: %s' % __name__)71 logger.debug('Added a stderr logging handler to logger: %s', __name__)72 return handler7374# ... Clean up.75del NullHandler
18 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+11 added-12 removed
201 unmodified lines
202 """203 Return a fresh :class:`HTTPConnection`.204 """205 self.num_connections += 1206 log.info("Starting new HTTP connection (%d): %s" %207 (self.num_connections, self.host))206 log.info("Starting new HTTP connection (%d): %s",207 self.num_connections, self.host)208209 conn = self.ConnectionCls(host=self.host, port=self.port,210 timeout=self.timeout.connect_timeout,211 strict=self.strict, **self.conn_kw)
26 unmodified lines
238 pass # Oh well, we'll create a new connection then239240 # If this is a persistent connection, check if it got disconnected241 if conn and is_connection_dropped(conn):242 log.info("Resetting dropped connection: %s" % self.host)242 log.info("Resetting dropped connection: %s", self.host)243 conn.close()244 if getattr(conn, 'auto_open', 1) == 0:245 # This is a proxied connection that has been mutated by246 # httplib._tunnel() and cannot be reused (since it would
24 unmodified lines
271 pass272 except Full:273 # This should never happen if self.block == True274 log.warning(275 "Connection pool is full, discarding connection: %s" %275 "Connection pool is full, discarding connection: %s",276 self.host)277278 # Connection never got put back into the pool, close it.279 if conn:
101 unmodified lines
381 raise382383 # AppEngine doesn't have a version attr.384 http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')385 log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,386 httplib_response.status,387 httplib_response.length))385 log.debug("\"%s %s %s\" %s %s", method, url, http_version,386 httplib_response.status, httplib_response.length)387388 try:389 assert_header_parsing(httplib_response.msg)390 except HeaderParsingError as hpe: # Platform-specific: Python 3
229 unmodified lines
620621 if not conn:622 # Try again623 log.warning("Retrying (%r) after connection "625 "broken by '%r': %s" % (retries, err, url))624 "broken by '%r': %s", retries, err, url)625 return self.urlopen(method, url, body, headers, retries,626 redirect, assert_same_host,627 timeout=timeout, pool_timeout=pool_timeout,628 release_conn=release_conn, **response_kw)
13 unmodified lines
642 response.release_conn()643 raise644 return response645647 log.info("Redirecting %s -> %s" % (url, redirect_location))646 log.info("Redirecting %s -> %s", url, redirect_location)647 return self.urlopen(648 method, redirect_location, body, headers,649 retries=retries, redirect=redirect,650 assert_same_host=assert_same_host,
3 unmodified lines
654 # Check if we should retry the HTTP response.655 if retries.is_forced_retry(method, status_code=response.status):656 retries = retries.increment(method, url, response=response, _pool=self)657 retries.sleep()659 log.info("Forced retry: %s" % url)658 log.info("Forced retry: %s", url)659 return self.urlopen(660 method, url, body, headers,661 retries=retries, redirect=redirect,662 assert_same_host=assert_same_host,
89 unmodified lines
752 """753 Return a fresh :class:`httplib.HTTPSConnection`.754 """755 self.num_connections += 1757 log.info("Starting new HTTPS connection (%d): %s"758 % (self.num_connections, self.host))756 log.info("Starting new HTTPS connection (%d): %s",757 self.num_connections, self.host)758759 if not self.ConnectionCls or self.ConnectionCls is DummyConnection:760 raise SSLError("Can't connect to HTTPS URL because the SSL "761 "module is not available.")
56 unmodified lines
modified:requests/packages/urllib3/exceptions.py+8 added
178 unmodified lines
179 "Warned when making a HTTPS request without SNI available."180 pass181182183class DependencyWarning(HTTPWarning):184 """185 Warned when an attempt is made to import a module with missing optional186 dependencies.187 """188 pass189190191class ResponseNotChunked(ProtocolError, ValueError):192 "Response needs to be chunked in order to read it as chunks."193 pass194
15 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+10 added-7 removed
16 unmodified lines
1718__all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']192021pool_classes_by_scheme = {22 'http': HTTPConnectionPool,23 'https': HTTPSConnectionPool,24}2521log = logging.getLogger(__name__)2223SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',24 'ssl_version', 'ca_cert_dir')2526pool_classes_by_scheme = {27 'http': HTTPConnectionPool,28 'https': HTTPSConnectionPool,29}303132class PoolManager(RequestMethods):33 """34 Allows for arbitrary requests while transparently keeping track of35 necessary connection pools for you.
28 unmodified lines
64 self.connection_pool_kw = connection_pool_kw65 self.pools = RecentlyUsedContainer(num_pools,66 dispose_func=lambda p: p.close())6768 # Locally set the pool classes so other PoolManagers can override them.69 self.pool_classes_by_scheme = pool_classes_by_scheme7071 def __enter__(self):72 return self7374 def __exit__(self, exc_type, exc_val, exc_tb):
8 unmodified lines
83 This method is used to actually create the connection pools handed out84 by :meth:`connection_from_url` and companion methods. It is intended85 to be overridden for customization.86 """84 pool_cls = pool_classes_by_scheme[scheme]87 pool_cls = self.pool_classes_by_scheme[scheme]88 kwargs = self.connection_pool_kw89 if scheme == 'http':90 kwargs = self.connection_pool_kw.copy()91 for kw in SSL_KEYWORDS:
96 unmodified lines
188189 kw['retries'] = retries190 kw['redirect'] = redirect191189 log.info("Redirecting %s -> %s" % (url, redirect_location))192 log.info("Redirecting %s -> %s", url, redirect_location)193 return self.urlopen(method, redirect_location, **kw)194195196class ProxyManager(PoolManager):
88 unmodified lines