Skip to content
Myr

updated urllib3 (v1.15.1)

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

authored by Kenneth Reitz · committed by Kenneth Reitz · parent a5da4f3 · Browse files · 14 files+267 added−65 removed
This commit

State

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

Diff stats

14 files+267 added−65 removed

  • other:+267 added−65 removed

14 files+267 added−65 removed

modified:requests/packages/urllib3/contrib/appengine.py+1 added-1 removed
68 unmodified lines
6970 warnings.warn(71 "urllib3 is using URLFetch on Google App Engine sandbox instead "72 "of sockets. To use sockets directly instead of URLFetch see "73 "https://urllib3.readthedocs.io/en/latest/contrib.html.",73 "https://urllib3.readthedocs.org/en/latest/contrib.html.",74 AppEnginePlatformWarning)7576 RequestMethods.__init__(self, headers)77 self.validate_certificate = validate_certificate
154 unmodified lines
modified:requests/packages/urllib3/contrib/pyopenssl.py+56 added-8 removed
52 unmodified lines
5354import OpenSSL.SSL55from pyasn1.codec.der import decoder as der_decoder56from pyasn1.type import univ, constraint57from socket import _fileobject, timeout, error as SocketError57from socket import timeout, error as SocketError5859try: # Platform-specific: Python 260 from socket import _fileobject61except ImportError: # Platform-specific: Python 362 _fileobject = None63 from urllib3.packages.backports.makefile import backport_makefile6465import ssl66import select67import six6869from .. import connection70from .. import util71
25 unmodified lines
97 ssl.CERT_REQUIRED:98 OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,99}10093DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS101DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS.encode('ascii')102103# OpenSSL will only write 16K at a time104SSL_WRITE_BLOCKSIZE = 16384105
5 unmodified lines
111 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'112113 connection.ssl_wrap_socket = ssl_wrap_socket114 util.HAS_SNI = HAS_SNI115 util.IS_PYOPENSSL = True116117118def extract_from_urllib3():119 'Undo monkey-patching by :func:`inject_into_urllib3`.'120121 connection.ssl_wrap_socket = orig_connection_ssl_wrap_socket122 util.HAS_SNI = orig_util_HAS_SNI123 util.IS_PYOPENSSL = False124125126# Note: This is a slightly bug-fixed version of same from ndg-httpsclient.127class SubjectAltName(BaseSubjectAltName):
16 unmodified lines
144 general_names = SubjectAltName()145 for i in range(peer_cert.get_extension_count()):146 ext = peer_cert.get_extension(i)147 ext_name = ext.get_short_name()138 if ext_name != 'subjectAltName':148 if ext_name != b'subjectAltName':149 continue150151 # PyOpenSSL returns extension data in ASN.1 encoded form152 ext_dat = ext.get_data()
23 unmodified lines
176 self.connection = connection177 self.socket = socket178 self.suppress_ragged_eofs = suppress_ragged_eofs179 self._makefile_refs = 0180 self._closed = False181182 def fileno(self):183 return self.socket.fileno()184174 def makefile(self, mode, bufsize=-1):175 self._makefile_refs += 1176 return _fileobject(self, mode, bufsize, close=True)185 # Copy-pasted from Python 3.5 source code186 def _decref_socketios(self):187 if self._makefile_refs > 0:188 self._makefile_refs -= 1189 if self._closed:190 self.close()191192 def recv(self, *args, **kwargs):193 try:194 data = self.connection.recv(*args, **kwargs)195 except OpenSSL.SSL.SysCallError as e:196 if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):197 return b''198 else:185 raise SocketError(e)199 raise SocketError(str(e))200 except OpenSSL.SSL.ZeroReturnError as e:201 if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:202 return b''203 else:
7 unmodified lines
211 return self.recv(*args, **kwargs)212 else:213 return data214215 def recv_into(self, *args, **kwargs):216 try:217 return self.connection.recv_into(*args, **kwargs)218 except OpenSSL.SSL.SysCallError as e:219 if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):220 return 0221 else:222 raise SocketError(str(e))223 except OpenSSL.SSL.ZeroReturnError as e:224 if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:225 return 0226 else:227 raise228 except OpenSSL.SSL.WantReadError:229 rd, wd, ed = select.select(230 [self.socket], [], [], self.socket.gettimeout())231 if not rd:232 raise timeout('The read operation timed out')233 else:234 return self.recv_into(*args, **kwargs)235236 def settimeout(self, timeout):237 return self.socket.settimeout(timeout)238239 def _send_until_done(self, data):
19 unmodified lines
259260 def close(self):261 if self._makefile_refs < 1:262 try:263 self._closed = True264 return self.connection.close()265 except OpenSSL.SSL.Error:266 return267 else:
29 unmodified lines
297 else:298 self._makefile_refs -= 1299300301if _fileobject: # Platform-specific: Python 2302 def makefile(self, mode, bufsize=-1):303 self._makefile_refs += 1304 return _fileobject(self, mode, bufsize, close=True)305else: # Platform-specific: Python 3306 makefile = backport_makefile307308WrappedSocket.makefile = makefile309310311def _verify_callback(cnx, x509, err_no, err_depth, return_code):312 return err_no == 0313314
15 unmodified lines
330 raise ssl.SSLError('bad ca_certs: %r' % ca_certs, e)331 else:332 ctx.set_default_verify_paths()333288 # Disable TLS compression to migitate CRIME attack (issue #309)334 # Disable TLS compression to mitigate CRIME attack (issue #309)335 OP_NO_COMPRESSION = 0x20000336 ctx.set_options(OP_NO_COMPRESSION)337338 # Set list of supported ciphersuites.339 ctx.set_cipher_list(DEFAULT_SSL_CIPHER_LIST)340341 cnx = OpenSSL.SSL.Connection(ctx, sock)342 if isinstance(server_hostname, six.text_type): # Platform-specific: Python 3343 server_hostname = server_hostname.encode('utf-8')344 cnx.set_tlsext_host_name(server_hostname)345 cnx.set_connect_state()346 while True:347 try:
11 unmodified lines
added:requests/packages/urllib3/packages/backports/__init__.py
added:requests/packages/urllib3/packages/backports/makefile.py+53 added
1# -*- coding: utf-8 -*-2"""3backports.makefile4~~~~~~~~~~~~~~~~~~56Backports the Python 3 ``socket.makefile`` method for use with anything that7wants to create a "fake" socket object.8"""9import io1011from socket import SocketIO121314def backport_makefile(self, mode="r", buffering=None, encoding=None,15 errors=None, newline=None):16 """17 Backport of ``socket.makefile`` from Python 3.5.18 """19 if not set(mode) <= set(["r", "w", "b"]):20 raise ValueError(21 "invalid mode %r (only r, w, b allowed)" % (mode,)22 )23 writing = "w" in mode24 reading = "r" in mode or not writing25 assert reading or writing26 binary = "b" in mode27 rawmode = ""28 if reading:29 rawmode += "r"30 if writing:31 rawmode += "w"32 raw = SocketIO(self, rawmode)33 self._makefile_refs += 134 if buffering is None:35 buffering = -136 if buffering < 0:37 buffering = io.DEFAULT_BUFFER_SIZE38 if buffering == 0:39 if not binary:40 raise ValueError("unbuffered streams must be binary")41 return raw42 if reading and writing:43 buffer = io.BufferedRWPair(raw, raw, buffering)44 elif reading:45 buffer = io.BufferedReader(raw, buffering)46 else:47 assert writing48 buffer = io.BufferedWriter(raw, buffering)49 if binary:50 return buffer51 text = io.TextIOWrapper(buffer, encoding, errors, newline)52 text.mode = mode53 return text
deleted:requests/packages/urllib3/packages/ssl_match_hostname/.gitignore-1 removed
1env
modified:requests/packages/urllib3/util/__init__.py+2 added
4 unmodified lines
5from .response import is_fp_closed6from .ssl_ import (7 SSLContext,8 HAS_SNI,9 IS_PYOPENSSL,10 assert_fingerprint,11 resolve_cert_reqs,12 resolve_ssl_version,13 ssl_wrap_socket,
12 unmodified lines
26)2728__all__ = (29 'HAS_SNI',30 'IS_PYOPENSSL',31 'SSLContext',32 'Retry',33 'Timeout',34 'Url',
12 unmodified lines
modified:requests/packages/urllib3/util/retry.py+9 added-1 removed
100 unmodified lines
101102 :param bool raise_on_redirect: Whether, if the number of redirects is103 exhausted, to raise a MaxRetryError, or to return a response with a104 response code in the 3xx range.105106 :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:107 whether we should raise an exception, or return a response,108 if status falls in ``status_forcelist`` range and retries have109 been exhausted.110 """111112 DEFAULT_METHOD_WHITELIST = frozenset([113 'HEAD', 'GET', 'PUT', 'DELETE', 'OPTIONS', 'TRACE'])
2 unmodified lines
116 BACKOFF_MAX = 120117118 def __init__(self, total=10, connect=None, read=None, redirect=None,119 method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None,115 backoff_factor=0, raise_on_redirect=True, _observed_errors=0):120 backoff_factor=0, raise_on_redirect=True, raise_on_status=True,121 _observed_errors=0):122123 self.total = total124 self.connect = connect125 self.read = read
6 unmodified lines
132 self.status_forcelist = status_forcelist or set()133 self.method_whitelist = method_whitelist134 self.backoff_factor = backoff_factor135 self.raise_on_redirect = raise_on_redirect136 self.raise_on_status = raise_on_status137 self._observed_errors = _observed_errors # TODO: use .history instead?138139 def new(self, **kw):140 params = dict(
2 unmodified lines
143 method_whitelist=self.method_whitelist,144 status_forcelist=self.status_forcelist,145 backoff_factor=self.backoff_factor,146 raise_on_redirect=self.raise_on_redirect,147 raise_on_status=self.raise_on_status,148 _observed_errors=self._observed_errors,149 )150 params.update(kw)151 return type(self)(**params)
143 unmodified lines
modified:requests/packages/urllib3/util/ssl_.py+7 added-5 removed
10 unmodified lines
1112SSLContext = None13HAS_SNI = False14create_default_context = None15IS_PYOPENSSL = False1617# Maps the length of a digest to a possible hash function producing this digest18HASHFUNC_MAP = {19 32: md5,
94 unmodified lines
114 def wrap_socket(self, socket, server_hostname=None, server_side=False):115 warnings.warn(116 'A true SSLContext object is not available. This prevents '117 'urllib3 from configuring SSL appropriately and may cause '117 'certain SSL connections to fail. For more information, see '118 'https://urllib3.readthedocs.io/en/latest/security.html'118 'certain SSL connections to fail. You can upgrade to a newer '119 'version of Python to solve this. For more information, see '120 'https://urllib3.readthedocs.org/en/latest/security.html'121 '#insecureplatformwarning.',122 InsecurePlatformWarning123 )124 kwargs = {
185 unmodified lines
310 warnings.warn(311 'An HTTPS request has been made, but the SNI (Subject Name '312 'Indication) extension to TLS is not available on this platform. '313 'This may cause the server to present an incorrect TLS '312 'certificate, which can cause validation failures. For more '313 'information, see '314 'https://urllib3.readthedocs.io/en/latest/security.html'314 'certificate, which can cause validation failures. You can upgrade to '315 'a newer version of Python to solve this. For more information, see '316 'https://urllib3.readthedocs.org/en/latest/security.html'317 '#snimissingwarning.',318 SNIMissingWarning319 )320 return context.wrap_socket(sock)
modified:requests/packages/urllib3/__init__.py+7 added-3 removed
1"""2urllib3 - Thread-safe connection pooling and re-using.3"""45from __future__ import absolute_import6import warnings78from .connectionpool import (
22 unmodified lines
31 pass3233__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'34__license__ = 'MIT'34__version__ = 'dev'35__version__ = '1.15.1'3637__all__ = (38 'HTTPConnectionPool',39 'HTTPSConnectionPool',
34 unmodified lines
74# ... Clean up.75del NullHandler767778# All warning filters *must* be appended unless you're really certain that they79# shouldn't be: otherwise, it's very hard for users to use most Python80# mechanisms to silence them.81# SecurityWarning's always go off by default.82warnings.simplefilter('always', exceptions.SecurityWarning, append=True)83# SubjectAltNameWarning's should go off once per host80warnings.simplefilter('default', exceptions.SubjectAltNameWarning)84warnings.simplefilter('default', exceptions.SubjectAltNameWarning, append=True)85# InsecurePlatformWarning's don't vary between requests, so we keep it default.86warnings.simplefilter('default', exceptions.InsecurePlatformWarning,87 append=True)88# SNIMissingWarnings should go off only once.85warnings.simplefilter('default', exceptions.SNIMissingWarning)89warnings.simplefilter('default', exceptions.SNIMissingWarning, append=True)909192def disable_warnings(category=exceptions.HTTPWarning):93 """
3 unmodified lines
modified:requests/packages/urllib3/_collections.py+1 added-1 removed
132 unmodified lines
133 """134135 def __init__(self, headers=None, **kwargs):136 super(HTTPHeaderDict, self).__init__()137 self._container = {}137 self._container = OrderedDict()138 if headers is not None:139 if isinstance(headers, HTTPHeaderDict):140 self._copy_from(headers)141 else:
183 unmodified lines
modified:requests/packages/urllib3/connection.py+53 added-11 removed
1from __future__ import absolute_import2import datetime3import logging4import os5import sys6import socket7from socket import error as SocketError, timeout as SocketTimeout
30 unmodified lines
38 ConnectTimeoutError,39 SubjectAltNameWarning,40 SystemTimeWarning,41)41from .packages.ssl_match_hostname import match_hostname42from .packages.ssl_match_hostname import match_hostname, CertificateError4344from .util.ssl_ import (45 resolve_cert_reqs,46 resolve_ssl_version,
3 unmodified lines
505152from .util import connection5354from ._collections import HTTPHeaderDict5556log = logging.getLogger(__name__)5758port_by_scheme = {59 'http': 80,60 'https': 443,61}
104 unmodified lines
166 def connect(self):167 conn = self._new_conn()168 self._prepare_conn(conn)169170 def request_chunked(self, method, url, body=None, headers=None):171 """172 Alternative to the common request method, which sends the173 body with chunked encoding and not as one block174 """175 headers = HTTPHeaderDict(headers if headers is not None else {})176 skip_accept_encoding = 'accept-encoding' in headers177 self.putrequest(method, url, skip_accept_encoding=skip_accept_encoding)178 for header, value in headers.items():179 self.putheader(header, value)180 if 'transfer-encoding' not in headers:181 self.putheader('Transfer-Encoding', 'chunked')182 self.endheaders()183184 if body is not None:185 stringish_types = six.string_types + (six.binary_type,)186 if isinstance(body, stringish_types):187 body = (body,)188 for chunk in body:189 if not chunk:190 continue191 if not isinstance(chunk, six.binary_type):192 chunk = chunk.encode('utf8')193 len_str = hex(len(chunk))[2:]194 self.send(len_str.encode('utf-8'))195 self.send(b'\r\n')196 self.send(chunk)197 self.send(b'\r\n')198199 # After the if clause, to always have a closed body200 self.send(b'0\r\n\r\n')201202203class HTTPSConnection(HTTPConnection):204 default_port = port_by_scheme['https']205206 def __init__(self, host, port=None, key_file=None, cert_file=None,
94 unmodified lines
301 'deprecated by RFC 2818. (See https://github.com/shazow/urllib3/issues/497 '302 'for details.)'.format(hostname)),303 SubjectAltNameWarning304 )305 _match_hostname(cert, self.assert_hostname or hostname)306269 # In case the hostname is an IPv6 address, strip the square270 # brackets from it before using it to validate. This is because271 # a certificate with an IPv6 address in it won't have square272 # brackets around that address. Sadly, match_hostname won't do this273 # for us: it expects the plain host part without any extra work274 # that might have been done to make it palatable to httplib.275 asserted_hostname = self.assert_hostname or hostname276 asserted_hostname = asserted_hostname.strip('[]')277 match_hostname(cert, asserted_hostname)278307 self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED or308 self.assert_fingerprint is not None)309310311def _match_hostname(cert, asserted_hostname):312 try:313 match_hostname(cert, asserted_hostname)314 except CertificateError as e:315 log.error(316 'Certificate did not match expected hostname: %s. '317 'Certificate: %s', asserted_hostname, cert318 )319 # Add cert to exception and reraise so client code can inspect320 # the cert when catching the exception, if they want to321 e._peer_cert = cert322 raise323324325if ssl:326 # Make a copy for testing.327 UnverifiedHTTPSConnection = HTTPSConnection328 HTTPSConnection = VerifiedHTTPSConnection
2 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+52 added-20 removed
67 unmodified lines
68 def __init__(self, host, port=None):69 if not host:70 raise LocationValueError("No host specified.")7172 # httplib doesn't like it when we include brackets in ipv6 addresses73 # Specifically, if we include brackets but also pass the port then74 # httplib crazily doubles up the square brackets on the Host header.75 # Instead, we need to make sure we never pass ``None`` as the port.76 # However, for backward compatibility reasons we can't actually77 # *assert* that.72 self.host = host78 self.host = host.strip('[]')79 self.port = port8081 def __str__(self):82 return '%s(host=%r, port=%r)' % (type(self).__name__,
240 unmodified lines
323 # http://bugs.python.org/issue10272324 if 'timed out' in str(err) or 'did not complete (read)' in str(err): # Python 2.6325 raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)326321 def _make_request(self, conn, method, url, timeout=_Default,327 def _make_request(self, conn, method, url, timeout=_Default, chunked=False,328 **httplib_request_kw):329 """330 Perform a request on a given urllib connection object taken from our331 pool.
23 unmodified lines
355 raise356357 # conn.request() calls httplib.*.request, not the method in358 # urllib3.request. It also calls makefile (recv) on the socket.359 if chunked:360 conn.request_chunked(method, url, **httplib_request_kw)361 else:353 conn.request(method, url, **httplib_request_kw)362 conn.request(method, url, **httplib_request_kw)363364 # Reset the timeout for the recv() on the socket365 read_timeout = timeout_obj.read_timeout366
75 unmodified lines
442 return (scheme, host, port) == (self.scheme, self.host, self.port)443444 def urlopen(self, method, url, body=None, headers=None, retries=None,445 redirect=True, assert_same_host=True, timeout=_Default,437 pool_timeout=None, release_conn=None, **response_kw):446 pool_timeout=None, release_conn=None, chunked=False,447 **response_kw):448 """449 Get a connection from the pool and perform an HTTP request. This is the450 lowest level call for making a request, so you'll need to specify all451 the raw details.
68 unmodified lines
520 ``r.release_conn()`` on the response ``r`` to return the connection521 back into the pool. If None, it takes the value of522 ``response_kw.get('preload_content', True)``.523524 :param chunked:525 If True, urllib3 will send the body using chunked transfer526 encoding. Otherwise, urllib3 will send the body using the standard527 content-length form. Defaults to False.528529 :param \**response_kw:530 Additional parameters are passed to531 :meth:`urllib3.response.HTTPResponse.from_httplib`532 """
22 unmodified lines
555 # Must keep the exception bound to a separate variable or else Python 3556 # complains about UnboundLocalError.557 err = None558559 # Keep track of whether we cleanly exited the except block. This560 # ensures we do proper cleanup in finally.561 clean_exit = False562563 try:564 # Request a connection from the queue.565 timeout_obj = self._get_timeout(timeout)566 conn = self._get_conn(timeout=pool_timeout)
6 unmodified lines
573574 # Make the request on the httplib connection object.575 httplib_response = self._make_request(conn, method, url,576 timeout=timeout_obj,558 body=body, headers=headers)577 body=body, headers=headers,578 chunked=chunked)579580 # If we're going to release the connection in ``finally:``, then561 # the request doesn't need to know about the connection. Otherwise581 # the response doesn't need to know about the connection. Otherwise582 # it will also try to release it and we'll have a double-release583 # mess.564 response_conn = not release_conn and conn584 response_conn = conn if not release_conn else None585586 # Import httplib's response into our own wrapper object587 response = HTTPResponse.from_httplib(httplib_response,588 pool=self,589 connection=response_conn,590 **response_kw)591572 # else:573 # The connection will be put back into the pool when574 # ``response.release_conn()`` is called (implicitly by575 # ``response.read()``)592 # Everything went great!593 clean_exit = True594595 except Empty:596 # Timed out by queue.597 raise EmptyPoolError(self, "No pool connections are available.")
1 unmodified line
599 except (BaseSSLError, CertificateError) as e:600 # Close the connection. If a connection is reused on which there601 # was a Certificate error, the next request will certainly raise602 # another Certificate error.585 conn = conn and conn.close()586 release_conn = True603 clean_exit = False604 raise SSLError(e)605606 except SSLError:607 # Treat SSLError separately from BaseSSLError to preserve608 # traceback.592 conn = conn and conn.close()593 release_conn = True609 clean_exit = False610 raise611612 except (TimeoutError, HTTPException, SocketError, ProtocolError) as e:613 # Discard the connection for these exceptions. It will be614 # be replaced during the next _get_conn() call.599 conn = conn and conn.close()600 release_conn = True615 clean_exit = False616617 if isinstance(e, (SocketError, NewConnectionError)) and self.proxy:618 e = ProxyError('Cannot connect to proxy.', e)619 elif isinstance(e, (SocketError, HTTPException)):
6 unmodified lines
626 # Keep track of the error for the retry warning.627 err = e628629 finally:630 if not clean_exit:631 # We hit some kind of exception, handled or otherwise. We need632 # to throw the connection away unless explicitly told not to.633 # Close the connection, set the variable to None, and make sure634 # we put the None back in the pool to avoid leaking it.635 conn = conn and conn.close()636 release_conn = True637638 if release_conn:639 # Put the connection back to be reused. If the connection is640 # expired then it will be None, which will get replaced with a641 # fresh connection during _get_conn.
33 unmodified lines
675 release_conn=release_conn, **response_kw)676677 # Check if we should retry the HTTP response.678 if retries.is_forced_retry(method, status_code=response.status):679 try:656 retries = retries.increment(method, url, response=response, _pool=self)680 retries = retries.increment(method, url, response=response, _pool=self)681 except MaxRetryError:682 if retries.raise_on_status:683 # Release the connection for this response, since we're not684 # returning it to be released manually.685 response.release_conn()686 raise687 return response688 retries.sleep()689 log.info("Forced retry: %s", url)690 return self.urlopen(691 method, url, body, headers,
79 unmodified lines
771 set_tunnel = conn.set_tunnel772 except AttributeError: # Platform-specific: Python 2.6773 set_tunnel = conn._set_tunnel774744 if sys.version_info <= (2, 6, 4) and not self.proxy_headers: # Python 2.6.4 and older775 if sys.version_info <= (2, 6, 4) and not self.proxy_headers: # Python 2.6.4 and older776 set_tunnel(self.host, self.port)777 else:778 set_tunnel(self.host, self.port, self.proxy_headers)779
36 unmodified lines
816 if not conn.is_verified:817 warnings.warn((818 'Unverified HTTPS request is being made. '819 'Adding certificate verification is strongly advised. See: '789 'https://urllib3.readthedocs.io/en/latest/security.html'),820 'https://urllib3.readthedocs.org/en/latest/security.html'),821 InsecureRequestWarning)822823824def connection_from_url(url, **kw):
16 unmodified lines
841 >>> conn = connection_from_url('http://google.com/')842 >>> r = conn.request('GET', '/')843 """844 scheme, host, port = get_host(url)845 port = port or port_by_scheme.get(scheme, 80)846 if scheme == 'https':847 return HTTPSConnectionPool(host, port=port, **kw)848 else:849 return HTTPConnectionPool(host, port=port, **kw)
modified:requests/packages/urllib3/fields.py+2 added-2 removed
34 unmodified lines
35 if not any(ch in value for ch in '"\\\r\n'):36 result = '%s="%s"' % (name, value)37 try:38 result.encode('ascii')39 except UnicodeEncodeError:39 except (UnicodeEncodeError, UnicodeDecodeError):40 pass41 else:42 return result43 if not six.PY3: # Python 2:43 if not six.PY3 and isinstance(value, six.text_type): # Python 2:44 value = value.encode('utf-8')45 value = email.utils.encode_rfc2231(value, 'utf-8')46 value = '%s*=%s' % (name, value)47 return value
131 unmodified lines
modified:requests/packages/urllib3/response.py+24 added-12 removed
219 unmodified lines
220 high-level api.221222 On exit, release the connection back to the pool.223 """224 clean_exit = False225226 try:227 try:228 yield229
14 unmodified lines
244 except (HTTPException, SocketError) as e:245 # This includes IncompleteRead.246 raise ProtocolError('Connection broken: %r' % e, e)247246 except Exception:247 # The response may not be closed but we're not going to use it anymore248 # so close it now to ensure that the connection is released back to the pool.249 if self._original_response and not self._original_response.isclosed():250 self._original_response.close()248 # If no exception is thrown, we should avoid cleaning up249 # unnecessarily.250 clean_exit = True251 finally:252 # If we didn't terminate cleanly, we need to throw away our253 # connection.254 if not clean_exit:255 # The response may not be closed but we're not going to use it256 # anymore so close it now to ensure that the connection is257 # released back to the pool.258 if self._original_response:259 self._original_response.close()260252 # Closing the response may not actually be sufficient to close253 # everything, so if we have a hold of the connection close that254 # too.255 if self._connection is not None:256 self._connection.close()261 # Closing the response may not actually be sufficient to close262 # everything, so if we have a hold of the connection close that263 # too.264 if self._connection:265 self._connection.close()266258 raise259 finally:267 # If we hold the original response but it's closed now, we should268 # return the connection back to the pool.269 if self._original_response and self._original_response.isclosed():270 self.release_conn()271272 def read(self, amt=None, decode_content=None, cache_content=False):
122 unmodified lines
395 def close(self):396 if not self.closed:397 self._fp.close()398399 if self._connection:400 self._connection.close()401402 @property403 def closed(self):404 if self._fp is None:405 return True
121 unmodified lines