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
Provenance
- Commit
cd84b3f- Tree
52dc782- Author
Cory Benfield <lukasaoz@gmail.com>- Committer
Cory Benfield <lukasaoz@gmail.com>- Parent
cbb0830
10 files changed+228 added−37 removed
modified:requests/packages/urllib3/contrib/appengine.py+10 added-2 removed
142 unmodified lines143 # 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 lines163 164 if content_encoding == 'deflate':165 del urlfetch_resp.headers['content-encoding']166 167+ 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)174+175 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 lines184 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.total39 unmodified linesmodified:requests/packages/urllib3/contrib/ntlmpool.py+10 added-10 removed
41 unmodified lines42 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)48 49 headers = {}50 headers['Connection'] = 'Keep-Alive'51 req_header = 'Authorization'3 unmodified lines55 56 # 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))66 67 # 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 = None16 unmodified lines86 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 linesadded:requests/packages/urllib3/contrib/socks.py+172 added
1+# -*- coding: utf-8 -*-2+"""3+SOCKS support for urllib34+~~~~~~~~~~~~~~~~~~~~~~~~~5+6+This contrib module contains provisional support for SOCKS proxies from within7+urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and8+SOCKS5. To enable its functionality, either install PySocks or install this9+module with the ``socks`` extra.10+11+Known Limitations:12+13+- 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+"""18+from __future__ import absolute_import19+20+try:21+ import socks22+except ImportError:23+ import warnings24+ from urllib3.exceptions import DependencyWarning25+26+ 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+ raise34+35+from socket import error as SocketError, timeout as SocketTimeout36+37+from urllib3.connection import (38+ HTTPConnection, HTTPSConnection39+)40+from urllib3.connectionpool import (41+ HTTPConnectionPool, HTTPSConnectionPool42+)43+from urllib3.exceptions import ConnectTimeoutError, NewConnectionError44+from urllib3.poolmanager import PoolManager45+from urllib3.util.url import parse_url46+47+try:48+ import ssl49+except ImportError:50+ ssl = None51+52+53+class 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)60+61+ 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_address68+69+ if self.socket_options:70+ extra_kw['socket_options'] = self.socket_options71+72+ 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+ )83+84+ except SocketTimeout as e:85+ raise ConnectTimeoutError(86+ self, "Connection to %s timed out. (connect timeout=%s)" %87+ (self.host, self.timeout))88+89+ 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+ )110+111+ except SocketError as e: # Defensive: PySocks should catch all these.112+ raise NewConnectionError(113+ self, "Failed to establish a new connection: %s" % e)114+115+ return conn116+117+118+# 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.122+class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection):123+ pass124+125+126+class SOCKSHTTPConnectionPool(HTTPConnectionPool):127+ ConnectionCls = SOCKSConnection128+129+130+class SOCKSHTTPSConnectionPool(HTTPSConnectionPool):131+ ConnectionCls = SOCKSHTTPSConnection132+133+134+class 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+ }143+144+ def __init__(self, proxy_url, username=None, password=None,145+ num_pools=10, headers=None, **connection_pool_kw):146+ parsed = parse_url(proxy_url)147+148+ 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+ )156+157+ self.proxy_url = proxy_url158+159+ 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_options167+168+ super(SOCKSProxyManager, self).__init__(169+ num_pools, headers, **connection_pool_kw170+ )171+172+ self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_schememodified:requests/packages/urllib3/util/response.py+1 added-1 removed
59 unmodified lines60 61 62 def 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.66 67 :param conn:68 :type conn: :class:`httplib.HTTPResponse`6 unmodified linesmodified:requests/packages/urllib3/util/retry.py+2 added-2 removed
151 unmodified lines152 return retries153 154 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_retries158 159 def get_backoff_time(self):160 """ Formula for computing the current backoff110 unmodified lines271 272 if new_retry.is_exhausted():273 raise MaxRetryError(_pool, url, error or ResponseError(cause))274 275- log.debug("Incremented Retry for (url='%s'): %r" % (url, new_retry))275+ log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)276 277 return new_retry278 279 def __repr__(self):7 unmodified linesmodified:requests/packages/urllib3/util/ssl_.py+2 added-1 removed
108 unmodified lines109 '2.7, 3.2, or later if you need this functionality.'110 )111 self.ciphers = cipher_suite112 113- 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 lines124 '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.6186 unmodified linesmodified:requests/packages/urllib3/__init__.py+2 added-2 removed
30 unmodified lines31 pass32 33 __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'34 __license__ = 'MIT'35-__version__ = '1.13.1'35+__version__ = '1.14'36 37 __all__ = (38 'HTTPConnectionPool',39 'HTTPSConnectionPool',27 unmodified lines67 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 handler73 74 # ... Clean up.75 del NullHandler18 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+11 added-12 removed
201 unmodified lines202 """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)208 209 conn = self.ConnectionCls(host=self.host, port=self.port,210 timeout=self.timeout.connect_timeout,211 strict=self.strict, **self.conn_kw)26 unmodified lines238 pass # Oh well, we'll create a new connection then239 240 # 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 would24 unmodified lines271 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)277 278 # Connection never got put back into the pool, close it.279 if conn:101 unmodified lines381 raise382 383 # 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)387 388 try:389 assert_header_parsing(httplib_response.msg)390 except HeaderParsingError as hpe: # Platform-specific: Python 3229 unmodified lines620 621 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 lines642 response.release_conn()643 raise644 return response645 647- 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 lines654 # 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 lines752 """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)758 759 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 linesmodified:requests/packages/urllib3/exceptions.py+8 added
178 unmodified lines179 "Warned when making a HTTPS request without SNI available."180 pass181 182 183+class DependencyWarning(HTTPWarning):184+ """185+ Warned when an attempt is made to import a module with missing optional186+ dependencies.187+ """188+ pass189+190+191 class ResponseNotChunked(ProtocolError, ValueError):192 "Response needs to be chunked in order to read it as chunks."193 pass194 15 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+10 added-7 removed
16 unmodified lines17 18 __all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']19 20 21-pool_classes_by_scheme = {22- 'http': HTTPConnectionPool,23- 'https': HTTPSConnectionPool,24-}25-21 log = logging.getLogger(__name__)22 23 SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',24 'ssl_version', 'ca_cert_dir')25 26+pool_classes_by_scheme = {27+ 'http': HTTPConnectionPool,28+ 'https': HTTPSConnectionPool,29+}30 31+32 class PoolManager(RequestMethods):33 """34 Allows for arbitrary requests while transparently keeping track of35 necessary connection pools for you.28 unmodified lines64 self.connection_pool_kw = connection_pool_kw65 self.pools = RecentlyUsedContainer(num_pools,66 dispose_func=lambda p: p.close())67 68+ # Locally set the pool classes so other PoolManagers can override them.69+ self.pool_classes_by_scheme = pool_classes_by_scheme70+71 def __enter__(self):72 return self73 74 def __exit__(self, exc_type, exc_val, exc_tb):8 unmodified lines83 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 lines188 189 kw['retries'] = retries190 kw['redirect'] = redirect191 189- 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)194 195 196 class ProxyManager(PoolManager):88 unmodified lines