Skip to content
Myr

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

12 files+123 added−67 removed

modified:requests/packages/urllib3/contrib/pyopenssl.py+3 added-3 removed
265 unmodified lines
266267268def 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 lines
modified:requests/packages/urllib3/util/connection.py+4 added-4 removed
78 unmodified lines
79 sock.bind(source_address)80 sock.connect(sa)81 return sock8283 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 = None8889 if err is not None:90 raise err91 else:92 raise socket.error("getaddrinfo returns an empty list")9192 raise socket.error("getaddrinfo returns an empty list")939495def _set_socket_options(sock, options):96 if options is None:97 return98
2 unmodified lines
modified:requests/packages/urllib3/util/response.py+1 added-4 removed
1try:2 import http.client as httplib3except ImportError:4 import httplib1from ..packages.six.moves import http_client as httplib23from ..exceptions import HeaderParsingError45
68 unmodified lines
modified:requests/packages/urllib3/util/ssl_.py+16 added-7 removed
73 unmodified lines
74 def load_cert_chain(self, certfile, keyfile):75 self.certfile = certfile76 self.keyfile = keyfile7778 def load_verify_locations(self, location):79 self.ca_certs = location78 def load_verify_locations(self, cafile=None, capath=None):79 self.ca_certs = cafile8081 if capath is not None:82 raise SSLError("CA directories not supported in older Pythons")8384 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 lines
242243244def 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`.251252 :param server_hostname:253 When SNI is supported, the expected hostname of the certificate254 :param ssl_context:
1 unmodified line
256 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)269262 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 raise281282 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 line
modified:requests/packages/urllib3/__init__.py+1 added-1 removed
2 unmodified lines
3"""45__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'6__license__ = 'MIT'7__version__ = 'dev'7__version__ = '1.12'8910from .connectionpool import (11 HTTPConnectionPool,
60 unmodified lines
modified:requests/packages/urllib3/_collections.py+29 added-29 removed
95 unmodified lines
96 with self.lock:97 return list(iterkeys(self._container))9899100_dict_setitem = dict.__setitem__101_dict_getitem = dict.__getitem__102_dict_delitem = dict.__delitem__103_dict_contains = dict.__contains__104_dict_setdefault = dict.setdefault105106107class HTTPHeaderDict(dict):100class 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 lines
131 '7'132 """133134 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 line
142 if kwargs:143 self.extend(kwargs)144145 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()]148149 def __getitem__(self, key):155 val = _dict_getitem(self, key.lower())150 val = self._container[key.lower()]151 return ', '.join(val[1:])152153 def __delitem__(self, key):159 return _dict_delitem(self, key.lower())154 del self._container[key.lower()]155156 def __contains__(self, key):162 return _dict_contains(self, key.lower())157 return key.lower() in self._container158159 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()))166167 def __ne__(self, other):168 return not self.__eq__(other)169174 values = MutableMapping.values175 get = MutableMapping.get176 update = MutableMapping.update177 170 if not PY3: # Python 2171 iterkeys = MutableMapping.iterkeys172 itervalues = MutableMapping.itervalues173174 __marker = object()175176 def __len__(self):177 return len(self._container)178179 def __iter__(self):180 # Only provide the originally cased names181 for vals in self._container.values():182 yield vals[0]183184 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 lines
215 """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]229230 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 items
2 unmodified lines
235 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 239240 if isinstance(other, HTTPHeaderDict):241 for key, val in other.iteritems():242 self.add(key, val)243 elif isinstance(other, Mapping):
12 unmodified lines
256 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 lines
275 return "%s(%s)" % (type(self).__name__, dict(self.itermerged()))276277 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] + val284285 def copy(self):286 clone = type(self)()287 clone._copy_from(self)
1 unmodified line
289290 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], val296297 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:])302303 def items(self):304 return list(self.iteritems())
1 unmodified line
306 @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 313314 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 319320 key, value = line.split(':', 1)321 headers.append((key, value.strip()))322323 return cls(headers)
modified:requests/packages/urllib3/connection.py+14 added-5 removed
1import datetime2import sys3import socket4from socket import timeout as SocketTimeout4from socket import error as SocketError, timeout as SocketTimeout5import warnings6from .packages import six78try: # Python 3
26 unmodified lines
35 pass363738from .exceptions import (39 NewConnectionError,40 ConnectTimeoutError,40 SystemTimeWarning,41 SubjectAltNameWarning,42 SystemTimeWarning,43)44from .packages.ssl_match_hostname import match_hostname4546from .util.ssl_ import (
86 unmodified lines
133 try:134 conn = connection.create_connection(135 (self.host, self.port), self.timeout, **extra_kw)136136 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))141142 except SocketError as e:143 raise NewConnectionError(144 self, "Failed to establish a new connection: %s" % e)145146 return conn147148 def _prepare_conn(self, conn):149 self.sock = conn
39 unmodified lines
189 SSL certification.190 """191 cert_reqs = None192 ca_certs = None193 ca_cert_dir = None194 ssl_version = None195 assert_fingerprint = None196197 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):201195 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'204205 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_fingerprint212213 def connect(self):
30 unmodified lines
244 # 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)251252 if self.assert_fingerprint:
25 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+12 added-8 removed
20 unmodified lines
21 HostChangedError,22 LocationValueError,23 MaxRetryError,24 ProxyError,25 ConnectTimeoutError,26 ReadTimeoutError,27 SSLError,28 TimeoutError,29 InsecureRequestWarning,30 NewConnectionError,31)32from .packages.ssl_match_hostname import CertificateError33from .packages import six34from .connection import (
388 unmodified lines
423 return True424425 # TODO: Add optional support for socket.gethostbyname checking.426 scheme, host, port = get_host(url)425 427428 # 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 lines
593 conn = conn and conn.close()594 release_conn = True595 raise596595 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 = True602601 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 lines
676 :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.679678 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 """685686 scheme = 'https'687 ConnectionCls = HTTPSConnection
4 unmodified lines
692 _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):697698 HTTPConnectionPool.__init__(self, host, port, strict, timeout, maxsize,699 block, headers, retries, _proxy, _proxy_headers,700 **conn_kw)
4 unmodified lines
705 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 lines
721 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 lines
modified:requests/packages/urllib3/exceptions.py+3 added
110 unmodified lines
111class ConnectTimeoutError(TimeoutError):112 "Raised when a socket timeout occurs while connecting to a server"113 pass114115class NewConnectionError(ConnectTimeoutError, PoolError):116 "Raised when we fail to establish a new connection. Usually ECONNREFUSED."117 pass118119class EmptyPoolError(PoolError):120 "Raised when a pool runs out of connections and no more are allowed."121 pass
72 unmodified lines
modified:requests/packages/urllib3/response.py+1 added-4 removed
1try:2 import http.client as httplib3except ImportError:4 import httplib1from contextlib import contextmanager2import zlib3import io4from socket import timeout as SocketTimeout
2 unmodified lines
7from .exceptions import (8 ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked9)10from .packages.six import string_types as basestring, binary_type, PY311from .packages.six.moves import http_client as httplib12from .connection import HTTPException, BaseSSLError13from .util.response import is_fp_closed, is_response_to_head1415
470 unmodified lines
modified:requests/__init__.py+2 added-2 removed
40 unmodified lines
4142"""4344__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 lines
modified:HISTORY.rst+37 added
1 unmodified line
23Release History4---------------562.8.0 (2015-10-05)7++++++++++++++++++89**Minor Improvements** (Backwards Compatible)1011- 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.2526**Bugfixes**2728- 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.3839**Updates**4041- Updated urllib3 to 1.12.42432.7.0 (2015-05-03)44++++++++++++++++++4546This is the first release that follows our new release process. For more, see
1022 unmodified lines