Merge pull request #2804 from Lukasa/final-2.8.0
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Final 2.8.0
authored by Ian Cordasco · committed by Ian Cordasco · parents 96e9490, ba7d093 · Browse files · 12 files·+123 added−67 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+123 added−67 removed
- other:+123 added−67 removed
Provenance
- Commit
e499b35- Tree
681d2e3- Author
Ian Cordasco <sigmavirus24@users.noreply.github.com>- Committer
Ian Cordasco <sigmavirus24@users.noreply.github.com>- Parent 1
96e9490- Parent 2
ba7d093
12 files changed+123 added−67 removed
modified:requests/packages/urllib3/contrib/pyopenssl.py+3 added-3 removed
265 unmodified lines266 267 268 def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,269 ca_certs=None, server_hostname=None,270- ssl_version=None):270+ ssl_version=None, ca_cert_dir=None):271 ctx = OpenSSL.SSL.Context(_openssl_versions[ssl_version])272 if certfile:273 keyfile = keyfile or certfile # Match behaviour of the normal python ssl library274 ctx.use_certificate_file(certfile)275 if keyfile:276 ctx.use_privatekey_file(keyfile)277 if cert_reqs != ssl.CERT_NONE:278 ctx.set_verify(_openssl_verify[cert_reqs], _verify_callback)279- if ca_certs:279+ if ca_certs or ca_cert_dir:280 try:281- ctx.load_verify_locations(ca_certs, None)281+ ctx.load_verify_locations(ca_certs, ca_cert_dir)282 except OpenSSL.SSL.Error as e:283 raise ssl.SSLError('bad ca_certs: %r' % ca_certs, e)284 else:285 ctx.set_default_verify_paths()24 unmodified linesmodified:requests/packages/urllib3/util/connection.py+4 added-4 removed
78 unmodified lines79 sock.bind(source_address)80 sock.connect(sa)81 return sock82 83- except socket.error as _:84- err = _83+ except socket.error as e:84+ err = e85 if sock is not None:86 sock.close()87 sock = None88 89 if err is not None:90 raise err91- else:92- raise socket.error("getaddrinfo returns an empty list")91 92+ raise socket.error("getaddrinfo returns an empty list")93 94+95 def _set_socket_options(sock, options):96 if options is None:97 return98 2 unmodified linesmodified:requests/packages/urllib3/util/response.py+1 added-4 removed
1-try:2- import http.client as httplib3-except ImportError:4- import httplib1+from ..packages.six.moves import http_client as httplib2 3 from ..exceptions import HeaderParsingError4 5 68 unmodified linesmodified:requests/packages/urllib3/util/ssl_.py+16 added-7 removed
73 unmodified lines74 def load_cert_chain(self, certfile, keyfile):75 self.certfile = certfile76 self.keyfile = keyfile77 78- def load_verify_locations(self, location):79- self.ca_certs = location78+ def load_verify_locations(self, cafile=None, capath=None):79+ self.ca_certs = cafile80 81+ if capath is not None:82+ raise SSLError("CA directories not supported in older Pythons")83+84 def set_ciphers(self, cipher_suite):85 if not self.supports_set_ciphers:86 raise TypeError(87 'Your version of Python does not support setting '154 unmodified lines242 243 244 def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,245 ca_certs=None, server_hostname=None,243- ssl_version=None, ciphers=None, ssl_context=None):246+ ssl_version=None, ciphers=None, ssl_context=None,247+ ca_cert_dir=None):248 """245- All arguments except for server_hostname and ssl_context have the same246- meaning as they do when using :func:`ssl.wrap_socket`.249+ All arguments except for server_hostname, ssl_context, and ca_cert_dir have250+ the same meaning as they do when using :func:`ssl.wrap_socket`.251 252 :param server_hostname:253 When SNI is supported, the expected hostname of the certificate254 :param ssl_context:1 unmodified line256 be created using :func:`create_urllib3_context`.257 :param ciphers:258 A string of ciphers we wish the client to support. This is not259 supported on Python 2.6 as the ssl module does not support it.260+ :param ca_cert_dir:261+ A directory containing CA certificates in multiple separate files, as262+ supported by OpenSSL's -CApath flag or the capath argument to263+ SSLContext.load_verify_locations().264 """265 context = ssl_context266 if context is None:267 context = create_urllib3_context(ssl_version, cert_reqs,268 ciphers=ciphers)269 262- if ca_certs:270+ if ca_certs or ca_cert_dir:271 try:264- context.load_verify_locations(ca_certs)272+ context.load_verify_locations(ca_certs, ca_cert_dir)273 except IOError as e: # Platform-specific: Python 2.6, 2.7, 3.2274 raise SSLError(e)275 # Py33 raises FileNotFoundError which subclasses OSError276 # These are not equivalent unless we check the errno attribute277 except OSError as e: # Platform-specific: Python 3.3 and beyond278 if e.errno == errno.ENOENT:279 raise SSLError(e)280 raise281+282 if certfile:283 context.load_cert_chain(certfile, keyfile)284 if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI285 return context.wrap_socket(sock, server_hostname=server_hostname)1 unmodified linemodified:requests/packages/urllib3/__init__.py+1 added-1 removed
2 unmodified lines3 """4 5 __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'6 __license__ = 'MIT'7-__version__ = 'dev'7+__version__ = '1.12'8 9 10 from .connectionpool import (11 HTTPConnectionPool,60 unmodified linesmodified:requests/packages/urllib3/_collections.py+29 added-29 removed
95 unmodified lines96 with self.lock:97 return list(iterkeys(self._container))98 99 100-_dict_setitem = dict.__setitem__101-_dict_getitem = dict.__getitem__102-_dict_delitem = dict.__delitem__103-_dict_contains = dict.__contains__104-_dict_setdefault = dict.setdefault105-106-107-class HTTPHeaderDict(dict):100+class HTTPHeaderDict(MutableMapping):101 """102 :param headers:103 An iterable of field-value pairs. Must not contain multiple field names104 when compared case-insensitively.26 unmodified lines131 '7'132 """133 134 def __init__(self, headers=None, **kwargs):142- dict.__init__(self)135+ super(HTTPHeaderDict, self).__init__()136+ self._container = {}137 if headers is not None:138 if isinstance(headers, HTTPHeaderDict):139 self._copy_from(headers)140 else:1 unmodified line142 if kwargs:143 self.extend(kwargs)144 145 def __setitem__(self, key, val):152- return _dict_setitem(self, key.lower(), (key, val))146+ self._container[key.lower()] = (key, val)147+ return self._container[key.lower()]148 149 def __getitem__(self, key):155- val = _dict_getitem(self, key.lower())150+ val = self._container[key.lower()]151 return ', '.join(val[1:])152 153 def __delitem__(self, key):159- return _dict_delitem(self, key.lower())154+ del self._container[key.lower()]155 156 def __contains__(self, key):162- return _dict_contains(self, key.lower())157+ return key.lower() in self._container158 159 def __eq__(self, other):160 if not isinstance(other, Mapping) and not hasattr(other, 'keys'):161 return False162 if not isinstance(other, type(self)):163 other = type(self)(other)169- return dict((k1, self[k1]) for k1 in self) == dict((k2, other[k2]) for k2 in other)164+ return (dict((k.lower(), v) for k, v in self.itermerged()) ==165+ dict((k.lower(), v) for k, v in other.itermerged()))166 167 def __ne__(self, other):168 return not self.__eq__(other)169 174- values = MutableMapping.values175- get = MutableMapping.get176- update = MutableMapping.update177- 170 if not PY3: # Python 2171 iterkeys = MutableMapping.iterkeys172 itervalues = MutableMapping.itervalues173 174 __marker = object()175 176+ def __len__(self):177+ return len(self._container)178+179+ def __iter__(self):180+ # Only provide the originally cased names181+ for vals in self._container.values():182+ yield vals[0]183+184 def pop(self, key, default=__marker):185 '''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.186 If key is not found, d is returned if given, otherwise KeyError is raised.187 '''27 unmodified lines215 """216 key_lower = key.lower()217 new_vals = key, val218 # Keep the common case aka no item present as fast as possible219- vals = _dict_setdefault(self, key_lower, new_vals)219+ vals = self._container.setdefault(key_lower, new_vals)220 if new_vals is not vals:221 # new_vals was not inserted, as there was a previous one222 if isinstance(vals, list):223 # If already several items got inserted, we have a list224 vals.append(val)225 else:226 # vals should be a tuple then, i.e. only one item so far227 # Need to convert the tuple to list for further extension228- _dict_setitem(self, key_lower, [vals[0], vals[1], val])228+ self._container[key_lower] = [vals[0], vals[1], val]229 230 def extend(self, *args, **kwargs):231 """Generic import function for any type of header-like object.232 Adapted version of MutableMapping.update in order to insert items2 unmodified lines235 if len(args) > 1:236 raise TypeError("extend() takes at most 1 positional "237 "arguments ({} given)".format(len(args)))238 other = args[0] if len(args) >= 1 else ()239- 239+240 if isinstance(other, HTTPHeaderDict):241 for key, val in other.iteritems():242 self.add(key, val)243 elif isinstance(other, Mapping):12 unmodified lines256 def getlist(self, key):257 """Returns a list of all the values for the named field. Returns an258 empty list if the key doesn't exist."""259 try:260- vals = _dict_getitem(self, key.lower())260+ vals = self._container[key.lower()]261 except KeyError:262 return []263 else:264 if isinstance(vals, tuple):10 unmodified lines275 return "%s(%s)" % (type(self).__name__, dict(self.itermerged()))276 277 def _copy_from(self, other):278 for key in other:279- val = _dict_getitem(other, key)279+ val = other.getlist(key)280 if isinstance(val, list):281 # Don't need to convert tuples282 val = list(val)283- _dict_setitem(self, key, val)283+ self._container[key.lower()] = [key] + val284 285 def copy(self):286 clone = type(self)()287 clone._copy_from(self)1 unmodified line289 290 def iteritems(self):291 """Iterate over all header lines, including duplicate ones."""292 for key in self:293- vals = _dict_getitem(self, key)293+ vals = self._container[key.lower()]294 for val in vals[1:]:295 yield vals[0], val296 297 def itermerged(self):298 """Iterate over all headers, merging duplicate ones together."""299 for key in self:300- val = _dict_getitem(self, key)300+ val = self._container[key.lower()]301 yield val[0], ', '.join(val[1:])302 303 def items(self):304 return list(self.iteritems())1 unmodified line306 @classmethod307 def from_httplib(cls, message): # Python 2308 """Read headers from a Python 2 httplib message object."""309 # python2.7 does not expose a proper API for exporting multiheaders310- # efficiently. This function re-reads raw lines from the message 310+ # efficiently. This function re-reads raw lines from the message311 # object and extracts the multiheaders properly.312 headers = []313- 313+314 for line in message.headers:315 if line.startswith((' ', '\t')):316 key, value = headers[-1]317 headers[-1] = (key, value + '\r\n' + line.rstrip())318 continue319- 319+320 key, value = line.split(':', 1)321 headers.append((key, value.strip()))322 323 return cls(headers)modified:requests/packages/urllib3/connection.py+14 added-5 removed
1 import datetime2 import sys3 import socket4-from socket import timeout as SocketTimeout4+from socket import error as SocketError, timeout as SocketTimeout5 import warnings6 from .packages import six7 8 try: # Python 326 unmodified lines35 pass36 37 38 from .exceptions import (39+ NewConnectionError,40 ConnectTimeoutError,40- SystemTimeWarning,41 SubjectAltNameWarning,42+ SystemTimeWarning,43 )44 from .packages.ssl_match_hostname import match_hostname45 46 from .util.ssl_ import (86 unmodified lines133 try:134 conn = connection.create_connection(135 (self.host, self.port), self.timeout, **extra_kw)136 136- except SocketTimeout:137+ except SocketTimeout as e:138 raise ConnectTimeoutError(139 self, "Connection to %s timed out. (connect timeout=%s)" %140 (self.host, self.timeout))141 142+ except SocketError as e:143+ raise NewConnectionError(144+ self, "Failed to establish a new connection: %s" % e)145+146 return conn147 148 def _prepare_conn(self, conn):149 self.sock = conn39 unmodified lines189 SSL certification.190 """191 cert_reqs = None192 ca_certs = None193+ ca_cert_dir = None194 ssl_version = None195 assert_fingerprint = None196 197 def set_cert(self, key_file=None, cert_file=None,198 cert_reqs=None, ca_certs=None,193- assert_hostname=None, assert_fingerprint=None):199+ assert_hostname=None, assert_fingerprint=None,200+ ca_cert_dir=None):201 195- if ca_certs and cert_reqs is None:202+ if (ca_certs or ca_cert_dir) and cert_reqs is None:203 cert_reqs = 'CERT_REQUIRED'204 205 self.key_file = key_file206 self.cert_file = cert_file207 self.cert_reqs = cert_reqs208 self.ca_certs = ca_certs209+ self.ca_cert_dir = ca_cert_dir210 self.assert_hostname = assert_hostname211 self.assert_fingerprint = assert_fingerprint212 213 def connect(self):30 unmodified lines244 # trusted_root_certs245 self.sock = ssl_wrap_socket(conn, self.key_file, self.cert_file,246 cert_reqs=resolved_cert_reqs,247 ca_certs=self.ca_certs,248+ ca_cert_dir=self.ca_cert_dir,249 server_hostname=hostname,250 ssl_version=resolved_ssl_version)251 252 if self.assert_fingerprint:25 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+12 added-8 removed
20 unmodified lines21 HostChangedError,22 LocationValueError,23 MaxRetryError,24 ProxyError,25+ ConnectTimeoutError,26 ReadTimeoutError,27 SSLError,28 TimeoutError,29 InsecureRequestWarning,30+ NewConnectionError,31 )32 from .packages.ssl_match_hostname import CertificateError33 from .packages import six34 from .connection import (388 unmodified lines423 return True424 425 # TODO: Add optional support for socket.gethostbyname checking.426 scheme, host, port = get_host(url)425- 427+428 # Use explicit default port for comparison when none is given429 if self.port and not port:430 port = port_by_scheme.get(scheme)431 elif not self.port and port == port_by_scheme.get(scheme):161 unmodified lines593 conn = conn and conn.close()594 release_conn = True595 raise596 595- except (TimeoutError, HTTPException, SocketError, ConnectionError) as e:597+ except (TimeoutError, HTTPException, SocketError, ProtocolError) as e:598 # Discard the connection for these exceptions. It will be599 # be replaced during the next _get_conn() call.600 conn = conn and conn.close()601 release_conn = True602 601- if isinstance(e, SocketError) and self.proxy:603+ if isinstance(e, (SocketError, NewConnectionError)) and self.proxy:604 e = ProxyError('Cannot connect to proxy.', e)605 elif isinstance(e, (SocketError, HTTPException)):606 e = ProtocolError('Connection aborted.', e)607 68 unmodified lines676 :class:`.VerifiedHTTPSConnection` uses one of ``assert_fingerprint``,677 ``assert_hostname`` and ``host`` in this order to verify connections.678 If ``assert_hostname`` is False, no verification is done.679 678- The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs`` and679- ``ssl_version`` are only used if :mod:`ssl` is available and are fed into680- :meth:`urllib3.util.ssl_wrap_socket` to upgrade the connection socket681- into an SSL socket.680+ The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``,681+ ``ca_cert_dir``, and ``ssl_version`` are only used if :mod:`ssl` is682+ available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade683+ the connection socket into an SSL socket.684 """685 686 scheme = 'https'687 ConnectionCls = HTTPSConnection4 unmodified lines692 _proxy=None, _proxy_headers=None,693 key_file=None, cert_file=None, cert_reqs=None,694 ca_certs=None, ssl_version=None,695 assert_hostname=None, assert_fingerprint=None,694- **conn_kw):696+ ca_cert_dir=None, **conn_kw):697 698 HTTPConnectionPool.__init__(self, host, port, strict, timeout, maxsize,699 block, headers, retries, _proxy, _proxy_headers,700 **conn_kw)4 unmodified lines705 self.key_file = key_file706 self.cert_file = cert_file707 self.cert_reqs = cert_reqs708 self.ca_certs = ca_certs709+ self.ca_cert_dir = ca_cert_dir710 self.ssl_version = ssl_version711 self.assert_hostname = assert_hostname712 self.assert_fingerprint = assert_fingerprint713 7 unmodified lines721 conn.set_cert(key_file=self.key_file,722 cert_file=self.cert_file,723 cert_reqs=self.cert_reqs,724 ca_certs=self.ca_certs,725+ ca_cert_dir=self.ca_cert_dir,726 assert_hostname=self.assert_hostname,727 assert_fingerprint=self.assert_fingerprint)728 conn.ssl_version = self.ssl_version729 87 unmodified linesmodified:requests/packages/urllib3/exceptions.py+3 added
110 unmodified lines111 class ConnectTimeoutError(TimeoutError):112 "Raised when a socket timeout occurs while connecting to a server"113 pass114 115+class NewConnectionError(ConnectTimeoutError, PoolError):116+ "Raised when we fail to establish a new connection. Usually ECONNREFUSED."117+ pass118 119 class EmptyPoolError(PoolError):120 "Raised when a pool runs out of connections and no more are allowed."121 pass72 unmodified linesmodified:requests/packages/urllib3/response.py+1 added-4 removed
1-try:2- import http.client as httplib3-except ImportError:4- import httplib1 from contextlib import contextmanager2 import zlib3 import io4 from socket import timeout as SocketTimeout2 unmodified lines7 from .exceptions import (8 ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked9 )10 from .packages.six import string_types as basestring, binary_type, PY311+from .packages.six.moves import http_client as httplib12 from .connection import HTTPException, BaseSSLError13 from .util.response import is_fp_closed, is_response_to_head14 15 470 unmodified linesmodified:requests/__init__.py+2 added-2 removed
40 unmodified lines41 42 """43 44 __title__ = 'requests'45-__version__ = '2.7.0'46-__build__ = 0x02070045+__version__ = '2.8.0'46+__build__ = 0x02080047 __author__ = 'Kenneth Reitz'48 __license__ = 'Apache 2.0'49 __copyright__ = 'Copyright 2015 Kenneth Reitz'50 27 unmodified linesmodified:HISTORY.rst+37 added
1 unmodified line2 3 Release History4 ---------------5 6+2.8.0 (2015-10-05)7+++++++++++++++++++8+9+**Minor Improvements** (Backwards Compatible)10+11+- Requests now supports per-host proxies. This allows the ``proxies``12+ dictionary to have entries of the form13+ ``{'<scheme>://<hostname>': '<proxy>'}``. Host-specific proxies will be used14+ in preference to the previously-supported scheme-specific ones, but the15+ previous syntax will continue to work.16+- ``Response.raise_for_status`` now prints the URL that failed as part of the17+ exception message.18+- ``requests.utils.get_netrc_auth`` now takes an ``raise_errors`` kwarg,19+ defaulting to ``False``. When ``True``, errors parsing ``.netrc`` files cause20+ exceptions to be thrown.21+- Change to bundled projects import logic to make it easier to unbundle22+ requests downstream.23+- Changed the default User-Agent string to avoid leaking data on Linux: now24+ contains only the requests version.25+26+**Bugfixes**27+28+- The ``json`` parameter to ``post()`` and friends will now only be used if29+ neither ``data`` nor ``files`` are present, consistent with the30+ documentation.31+- We now ignore empty fields in the ``NO_PROXY`` enviroment variable.32+- Fixed problem where ``httplib.BadStatusLine`` would get raised if combining33+ ``stream=True`` with ``contextlib.closing``.34+- Prevented bugs where we would attempt to return the same connection back to35+ the connection pool twice when sending a Chunked body.36+- Miscellaneous minor internal changes.37+- Digest Auth support is now thread safe.38+39+**Updates**40+41+- Updated urllib3 to 1.12.42+43 2.7.0 (2015-05-03)44 ++++++++++++++++++45 46 This is the first release that follows our new release process. For more, see1022 unmodified lines