Path: blob/master/venv/Lib/site-packages/urllib3/connectionpool.py
811 views
from __future__ import absolute_import1import errno2import logging3import sys4import warnings56from socket import error as SocketError, timeout as SocketTimeout7import socket8910from .exceptions import (11ClosedPoolError,12ProtocolError,13EmptyPoolError,14HeaderParsingError,15HostChangedError,16LocationValueError,17MaxRetryError,18ProxyError,19ReadTimeoutError,20SSLError,21TimeoutError,22InsecureRequestWarning,23NewConnectionError,24)25from .packages.ssl_match_hostname import CertificateError26from .packages import six27from .packages.six.moves import queue28from .connection import (29port_by_scheme,30DummyConnection,31HTTPConnection,32HTTPSConnection,33VerifiedHTTPSConnection,34HTTPException,35BaseSSLError,36)37from .request import RequestMethods38from .response import HTTPResponse3940from .util.connection import is_connection_dropped41from .util.request import set_file_position42from .util.response import assert_header_parsing43from .util.retry import Retry44from .util.timeout import Timeout45from .util.url import (46get_host,47parse_url,48Url,49_normalize_host as normalize_host,50_encode_target,51)52from .util.queue import LifoQueue535455xrange = six.moves.xrange5657log = logging.getLogger(__name__)5859_Default = object()606162# Pool objects63class ConnectionPool(object):64"""65Base class for all connection pools, such as66:class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.6768.. note::69ConnectionPool.urlopen() does not normalize or percent-encode target URIs70which is useful if your target server doesn't support percent-encoded71target URIs.72"""7374scheme = None75QueueCls = LifoQueue7677def __init__(self, host, port=None):78if not host:79raise LocationValueError("No host specified.")8081self.host = _normalize_host(host, scheme=self.scheme)82self._proxy_host = host.lower()83self.port = port8485def __str__(self):86return "%s(host=%r, port=%r)" % (type(self).__name__, self.host, self.port)8788def __enter__(self):89return self9091def __exit__(self, exc_type, exc_val, exc_tb):92self.close()93# Return False to re-raise any potential exceptions94return False9596def close(self):97"""98Close all pooled connections and disable the pool.99"""100pass101102103# This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252104_blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK}105106107class HTTPConnectionPool(ConnectionPool, RequestMethods):108"""109Thread-safe connection pool for one host.110111:param host:112Host used for this HTTP Connection (e.g. "localhost"), passed into113:class:`httplib.HTTPConnection`.114115:param port:116Port used for this HTTP Connection (None is equivalent to 80), passed117into :class:`httplib.HTTPConnection`.118119:param strict:120Causes BadStatusLine to be raised if the status line can't be parsed121as a valid HTTP/1.0 or 1.1 status line, passed into122:class:`httplib.HTTPConnection`.123124.. note::125Only works in Python 2. This parameter is ignored in Python 3.126127:param timeout:128Socket timeout in seconds for each individual connection. This can129be a float or integer, which sets the timeout for the HTTP request,130or an instance of :class:`urllib3.util.Timeout` which gives you more131fine-grained control over request timeouts. After the constructor has132been parsed, this is always a `urllib3.util.Timeout` object.133134:param maxsize:135Number of connections to save that can be reused. More than 1 is useful136in multithreaded situations. If ``block`` is set to False, more137connections will be created but they will not be saved once they've138been used.139140:param block:141If set to True, no more than ``maxsize`` connections will be used at142a time. When no free connections are available, the call will block143until a connection has been released. This is a useful side effect for144particular multithreaded situations where one does not want to use more145than maxsize connections per host to prevent flooding.146147:param headers:148Headers to include with all requests, unless other headers are given149explicitly.150151:param retries:152Retry configuration to use by default with requests in this pool.153154:param _proxy:155Parsed proxy URL, should not be used directly, instead, see156:class:`urllib3.connectionpool.ProxyManager`"157158:param _proxy_headers:159A dictionary with proxy headers, should not be used directly,160instead, see :class:`urllib3.connectionpool.ProxyManager`"161162:param \\**conn_kw:163Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,164:class:`urllib3.connection.HTTPSConnection` instances.165"""166167scheme = "http"168ConnectionCls = HTTPConnection169ResponseCls = HTTPResponse170171def __init__(172self,173host,174port=None,175strict=False,176timeout=Timeout.DEFAULT_TIMEOUT,177maxsize=1,178block=False,179headers=None,180retries=None,181_proxy=None,182_proxy_headers=None,183**conn_kw184):185ConnectionPool.__init__(self, host, port)186RequestMethods.__init__(self, headers)187188self.strict = strict189190if not isinstance(timeout, Timeout):191timeout = Timeout.from_float(timeout)192193if retries is None:194retries = Retry.DEFAULT195196self.timeout = timeout197self.retries = retries198199self.pool = self.QueueCls(maxsize)200self.block = block201202self.proxy = _proxy203self.proxy_headers = _proxy_headers or {}204205# Fill the queue up so that doing get() on it will block properly206for _ in xrange(maxsize):207self.pool.put(None)208209# These are mostly for testing and debugging purposes.210self.num_connections = 0211self.num_requests = 0212self.conn_kw = conn_kw213214if self.proxy:215# Enable Nagle's algorithm for proxies, to avoid packet fragmentation.216# We cannot know if the user has added default socket options, so we cannot replace the217# list.218self.conn_kw.setdefault("socket_options", [])219220def _new_conn(self):221"""222Return a fresh :class:`HTTPConnection`.223"""224self.num_connections += 1225log.debug(226"Starting new HTTP connection (%d): %s:%s",227self.num_connections,228self.host,229self.port or "80",230)231232conn = self.ConnectionCls(233host=self.host,234port=self.port,235timeout=self.timeout.connect_timeout,236strict=self.strict,237**self.conn_kw238)239return conn240241def _get_conn(self, timeout=None):242"""243Get a connection. Will return a pooled connection if one is available.244245If no connections are available and :prop:`.block` is ``False``, then a246fresh connection is returned.247248:param timeout:249Seconds to wait before giving up and raising250:class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and251:prop:`.block` is ``True``.252"""253conn = None254try:255conn = self.pool.get(block=self.block, timeout=timeout)256257except AttributeError: # self.pool is None258raise ClosedPoolError(self, "Pool is closed.")259260except queue.Empty:261if self.block:262raise EmptyPoolError(263self,264"Pool reached maximum size and no more connections are allowed.",265)266pass # Oh well, we'll create a new connection then267268# If this is a persistent connection, check if it got disconnected269if conn and is_connection_dropped(conn):270log.debug("Resetting dropped connection: %s", self.host)271conn.close()272if getattr(conn, "auto_open", 1) == 0:273# This is a proxied connection that has been mutated by274# httplib._tunnel() and cannot be reused (since it would275# attempt to bypass the proxy)276conn = None277278return conn or self._new_conn()279280def _put_conn(self, conn):281"""282Put a connection back into the pool.283284:param conn:285Connection object for the current host and port as returned by286:meth:`._new_conn` or :meth:`._get_conn`.287288If the pool is already full, the connection is closed and discarded289because we exceeded maxsize. If connections are discarded frequently,290then maxsize should be increased.291292If the pool is closed, then the connection will be closed and discarded.293"""294try:295self.pool.put(conn, block=False)296return # Everything is dandy, done.297except AttributeError:298# self.pool is None.299pass300except queue.Full:301# This should never happen if self.block == True302log.warning("Connection pool is full, discarding connection: %s", self.host)303304# Connection never got put back into the pool, close it.305if conn:306conn.close()307308def _validate_conn(self, conn):309"""310Called right before a request is made, after the socket is created.311"""312pass313314def _prepare_proxy(self, conn):315# Nothing to do for HTTP connections.316pass317318def _get_timeout(self, timeout):319""" Helper that always returns a :class:`urllib3.util.Timeout` """320if timeout is _Default:321return self.timeout.clone()322323if isinstance(timeout, Timeout):324return timeout.clone()325else:326# User passed us an int/float. This is for backwards compatibility,327# can be removed later328return Timeout.from_float(timeout)329330def _raise_timeout(self, err, url, timeout_value):331"""Is the error actually a timeout? Will raise a ReadTimeout or pass"""332333if isinstance(err, SocketTimeout):334raise ReadTimeoutError(335self, url, "Read timed out. (read timeout=%s)" % timeout_value336)337338# See the above comment about EAGAIN in Python 3. In Python 2 we have339# to specifically catch it and throw the timeout error340if hasattr(err, "errno") and err.errno in _blocking_errnos:341raise ReadTimeoutError(342self, url, "Read timed out. (read timeout=%s)" % timeout_value343)344345# Catch possible read timeouts thrown as SSL errors. If not the346# case, rethrow the original. We need to do this because of:347# http://bugs.python.org/issue10272348if "timed out" in str(err) or "did not complete (read)" in str(349err350): # Python < 2.7.4351raise ReadTimeoutError(352self, url, "Read timed out. (read timeout=%s)" % timeout_value353)354355def _make_request(356self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw357):358"""359Perform a request on a given urllib connection object taken from our360pool.361362:param conn:363a connection from one of our connection pools364365:param timeout:366Socket timeout in seconds for the request. This can be a367float or integer, which will set the same timeout value for368the socket connect and the socket read, or an instance of369:class:`urllib3.util.Timeout`, which gives you more fine-grained370control over your timeouts.371"""372self.num_requests += 1373374timeout_obj = self._get_timeout(timeout)375timeout_obj.start_connect()376conn.timeout = timeout_obj.connect_timeout377378# Trigger any extra validation we need to do.379try:380self._validate_conn(conn)381except (SocketTimeout, BaseSSLError) as e:382# Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.383self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)384raise385386# conn.request() calls httplib.*.request, not the method in387# urllib3.request. It also calls makefile (recv) on the socket.388if chunked:389conn.request_chunked(method, url, **httplib_request_kw)390else:391conn.request(method, url, **httplib_request_kw)392393# Reset the timeout for the recv() on the socket394read_timeout = timeout_obj.read_timeout395396# App Engine doesn't have a sock attr397if getattr(conn, "sock", None):398# In Python 3 socket.py will catch EAGAIN and return None when you399# try and read into the file pointer created by http.client, which400# instead raises a BadStatusLine exception. Instead of catching401# the exception and assuming all BadStatusLine exceptions are read402# timeouts, check for a zero timeout before making the request.403if read_timeout == 0:404raise ReadTimeoutError(405self, url, "Read timed out. (read timeout=%s)" % read_timeout406)407if read_timeout is Timeout.DEFAULT_TIMEOUT:408conn.sock.settimeout(socket.getdefaulttimeout())409else: # None or a value410conn.sock.settimeout(read_timeout)411412# Receive the response from the server413try:414try:415# Python 2.7, use buffering of HTTP responses416httplib_response = conn.getresponse(buffering=True)417except TypeError:418# Python 3419try:420httplib_response = conn.getresponse()421except BaseException as e:422# Remove the TypeError from the exception chain in423# Python 3 (including for exceptions like SystemExit).424# Otherwise it looks like a bug in the code.425six.raise_from(e, None)426except (SocketTimeout, BaseSSLError, SocketError) as e:427self._raise_timeout(err=e, url=url, timeout_value=read_timeout)428raise429430# AppEngine doesn't have a version attr.431http_version = getattr(conn, "_http_vsn_str", "HTTP/?")432log.debug(433'%s://%s:%s "%s %s %s" %s %s',434self.scheme,435self.host,436self.port,437method,438url,439http_version,440httplib_response.status,441httplib_response.length,442)443444try:445assert_header_parsing(httplib_response.msg)446except (HeaderParsingError, TypeError) as hpe: # Platform-specific: Python 3447log.warning(448"Failed to parse headers (url=%s): %s",449self._absolute_url(url),450hpe,451exc_info=True,452)453454return httplib_response455456def _absolute_url(self, path):457return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url458459def close(self):460"""461Close all pooled connections and disable the pool.462"""463if self.pool is None:464return465# Disable access to the pool466old_pool, self.pool = self.pool, None467468try:469while True:470conn = old_pool.get(block=False)471if conn:472conn.close()473474except queue.Empty:475pass # Done.476477def is_same_host(self, url):478"""479Check if the given ``url`` is a member of the same host as this480connection pool.481"""482if url.startswith("/"):483return True484485# TODO: Add optional support for socket.gethostbyname checking.486scheme, host, port = get_host(url)487if host is not None:488host = _normalize_host(host, scheme=scheme)489490# Use explicit default port for comparison when none is given491if self.port and not port:492port = port_by_scheme.get(scheme)493elif not self.port and port == port_by_scheme.get(scheme):494port = None495496return (scheme, host, port) == (self.scheme, self.host, self.port)497498def urlopen(499self,500method,501url,502body=None,503headers=None,504retries=None,505redirect=True,506assert_same_host=True,507timeout=_Default,508pool_timeout=None,509release_conn=None,510chunked=False,511body_pos=None,512**response_kw513):514"""515Get a connection from the pool and perform an HTTP request. This is the516lowest level call for making a request, so you'll need to specify all517the raw details.518519.. note::520521More commonly, it's appropriate to use a convenience method provided522by :class:`.RequestMethods`, such as :meth:`request`.523524.. note::525526`release_conn` will only behave as expected if527`preload_content=False` because we want to make528`preload_content=False` the default behaviour someday soon without529breaking backwards compatibility.530531:param method:532HTTP request method (such as GET, POST, PUT, etc.)533534:param body:535Data to send in the request body (useful for creating536POST requests, see HTTPConnectionPool.post_url for537more convenience).538539:param headers:540Dictionary of custom headers to send, such as User-Agent,541If-None-Match, etc. If None, pool headers are used. If provided,542these headers completely replace any pool-specific headers.543544:param retries:545Configure the number of retries to allow before raising a546:class:`~urllib3.exceptions.MaxRetryError` exception.547548Pass ``None`` to retry until you receive a response. Pass a549:class:`~urllib3.util.retry.Retry` object for fine-grained control550over different types of retries.551Pass an integer number to retry connection errors that many times,552but no other types of errors. Pass zero to never retry.553554If ``False``, then retries are disabled and any exception is raised555immediately. Also, instead of raising a MaxRetryError on redirects,556the redirect response will be returned.557558:type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.559560:param redirect:561If True, automatically handle redirects (status codes 301, 302,562303, 307, 308). Each redirect counts as a retry. Disabling retries563will disable redirect, too.564565:param assert_same_host:566If ``True``, will make sure that the host of the pool requests is567consistent else will raise HostChangedError. When False, you can568use the pool on an HTTP proxy and request foreign hosts.569570:param timeout:571If specified, overrides the default timeout for this one572request. It may be a float (in seconds) or an instance of573:class:`urllib3.util.Timeout`.574575:param pool_timeout:576If set and the pool is set to block=True, then this method will577block for ``pool_timeout`` seconds and raise EmptyPoolError if no578connection is available within the time period.579580:param release_conn:581If False, then the urlopen call will not release the connection582back into the pool once a response is received (but will release if583you read the entire contents of the response such as when584`preload_content=True`). This is useful if you're not preloading585the response's content immediately. You will need to call586``r.release_conn()`` on the response ``r`` to return the connection587back into the pool. If None, it takes the value of588``response_kw.get('preload_content', True)``.589590:param chunked:591If True, urllib3 will send the body using chunked transfer592encoding. Otherwise, urllib3 will send the body using the standard593content-length form. Defaults to False.594595:param int body_pos:596Position to seek to in file-like body in the event of a retry or597redirect. Typically this won't need to be set because urllib3 will598auto-populate the value when needed.599600:param \\**response_kw:601Additional parameters are passed to602:meth:`urllib3.response.HTTPResponse.from_httplib`603"""604if headers is None:605headers = self.headers606607if not isinstance(retries, Retry):608retries = Retry.from_int(retries, redirect=redirect, default=self.retries)609610if release_conn is None:611release_conn = response_kw.get("preload_content", True)612613# Check host614if assert_same_host and not self.is_same_host(url):615raise HostChangedError(self, url, retries)616617# Ensure that the URL we're connecting to is properly encoded618if url.startswith("/"):619url = six.ensure_str(_encode_target(url))620else:621url = six.ensure_str(parse_url(url).url)622623conn = None624625# Track whether `conn` needs to be released before626# returning/raising/recursing. Update this variable if necessary, and627# leave `release_conn` constant throughout the function. That way, if628# the function recurses, the original value of `release_conn` will be629# passed down into the recursive call, and its value will be respected.630#631# See issue #651 [1] for details.632#633# [1] <https://github.com/urllib3/urllib3/issues/651>634release_this_conn = release_conn635636# Merge the proxy headers. Only do this in HTTP. We have to copy the637# headers dict so we can safely change it without those changes being638# reflected in anyone else's copy.639if self.scheme == "http":640headers = headers.copy()641headers.update(self.proxy_headers)642643# Must keep the exception bound to a separate variable or else Python 3644# complains about UnboundLocalError.645err = None646647# Keep track of whether we cleanly exited the except block. This648# ensures we do proper cleanup in finally.649clean_exit = False650651# Rewind body position, if needed. Record current position652# for future rewinds in the event of a redirect/retry.653body_pos = set_file_position(body, body_pos)654655try:656# Request a connection from the queue.657timeout_obj = self._get_timeout(timeout)658conn = self._get_conn(timeout=pool_timeout)659660conn.timeout = timeout_obj.connect_timeout661662is_new_proxy_conn = self.proxy is not None and not getattr(663conn, "sock", None664)665if is_new_proxy_conn:666self._prepare_proxy(conn)667668# Make the request on the httplib connection object.669httplib_response = self._make_request(670conn,671method,672url,673timeout=timeout_obj,674body=body,675headers=headers,676chunked=chunked,677)678679# If we're going to release the connection in ``finally:``, then680# the response doesn't need to know about the connection. Otherwise681# it will also try to release it and we'll have a double-release682# mess.683response_conn = conn if not release_conn else None684685# Pass method to Response for length checking686response_kw["request_method"] = method687688# Import httplib's response into our own wrapper object689response = self.ResponseCls.from_httplib(690httplib_response,691pool=self,692connection=response_conn,693retries=retries,694**response_kw695)696697# Everything went great!698clean_exit = True699700except queue.Empty:701# Timed out by queue.702raise EmptyPoolError(self, "No pool connections are available.")703704except (705TimeoutError,706HTTPException,707SocketError,708ProtocolError,709BaseSSLError,710SSLError,711CertificateError,712) as e:713# Discard the connection for these exceptions. It will be714# replaced during the next _get_conn() call.715clean_exit = False716if isinstance(e, (BaseSSLError, CertificateError)):717e = SSLError(e)718elif isinstance(e, (SocketError, NewConnectionError)) and self.proxy:719e = ProxyError("Cannot connect to proxy.", e)720elif isinstance(e, (SocketError, HTTPException)):721e = ProtocolError("Connection aborted.", e)722723retries = retries.increment(724method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]725)726retries.sleep()727728# Keep track of the error for the retry warning.729err = e730731finally:732if not clean_exit:733# We hit some kind of exception, handled or otherwise. We need734# to throw the connection away unless explicitly told not to.735# Close the connection, set the variable to None, and make sure736# we put the None back in the pool to avoid leaking it.737conn = conn and conn.close()738release_this_conn = True739740if release_this_conn:741# Put the connection back to be reused. If the connection is742# expired then it will be None, which will get replaced with a743# fresh connection during _get_conn.744self._put_conn(conn)745746if not conn:747# Try again748log.warning(749"Retrying (%r) after connection broken by '%r': %s", retries, err, url750)751return self.urlopen(752method,753url,754body,755headers,756retries,757redirect,758assert_same_host,759timeout=timeout,760pool_timeout=pool_timeout,761release_conn=release_conn,762chunked=chunked,763body_pos=body_pos,764**response_kw765)766767# Handle redirect?768redirect_location = redirect and response.get_redirect_location()769if redirect_location:770if response.status == 303:771method = "GET"772773try:774retries = retries.increment(method, url, response=response, _pool=self)775except MaxRetryError:776if retries.raise_on_redirect:777response.drain_conn()778raise779return response780781response.drain_conn()782retries.sleep_for_retry(response)783log.debug("Redirecting %s -> %s", url, redirect_location)784return self.urlopen(785method,786redirect_location,787body,788headers,789retries=retries,790redirect=redirect,791assert_same_host=assert_same_host,792timeout=timeout,793pool_timeout=pool_timeout,794release_conn=release_conn,795chunked=chunked,796body_pos=body_pos,797**response_kw798)799800# Check if we should retry the HTTP response.801has_retry_after = bool(response.getheader("Retry-After"))802if retries.is_retry(method, response.status, has_retry_after):803try:804retries = retries.increment(method, url, response=response, _pool=self)805except MaxRetryError:806if retries.raise_on_status:807response.drain_conn()808raise809return response810811response.drain_conn()812retries.sleep(response)813log.debug("Retry: %s", url)814return self.urlopen(815method,816url,817body,818headers,819retries=retries,820redirect=redirect,821assert_same_host=assert_same_host,822timeout=timeout,823pool_timeout=pool_timeout,824release_conn=release_conn,825chunked=chunked,826body_pos=body_pos,827**response_kw828)829830return response831832833class HTTPSConnectionPool(HTTPConnectionPool):834"""835Same as :class:`.HTTPConnectionPool`, but HTTPS.836837When Python is compiled with the :mod:`ssl` module, then838:class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,839instead of :class:`.HTTPSConnection`.840841:class:`.VerifiedHTTPSConnection` uses one of ``assert_fingerprint``,842``assert_hostname`` and ``host`` in this order to verify connections.843If ``assert_hostname`` is False, no verification is done.844845The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``,846``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl`847is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade848the connection socket into an SSL socket.849"""850851scheme = "https"852ConnectionCls = HTTPSConnection853854def __init__(855self,856host,857port=None,858strict=False,859timeout=Timeout.DEFAULT_TIMEOUT,860maxsize=1,861block=False,862headers=None,863retries=None,864_proxy=None,865_proxy_headers=None,866key_file=None,867cert_file=None,868cert_reqs=None,869key_password=None,870ca_certs=None,871ssl_version=None,872assert_hostname=None,873assert_fingerprint=None,874ca_cert_dir=None,875**conn_kw876):877878HTTPConnectionPool.__init__(879self,880host,881port,882strict,883timeout,884maxsize,885block,886headers,887retries,888_proxy,889_proxy_headers,890**conn_kw891)892893self.key_file = key_file894self.cert_file = cert_file895self.cert_reqs = cert_reqs896self.key_password = key_password897self.ca_certs = ca_certs898self.ca_cert_dir = ca_cert_dir899self.ssl_version = ssl_version900self.assert_hostname = assert_hostname901self.assert_fingerprint = assert_fingerprint902903def _prepare_conn(self, conn):904"""905Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`906and establish the tunnel if proxy is used.907"""908909if isinstance(conn, VerifiedHTTPSConnection):910conn.set_cert(911key_file=self.key_file,912key_password=self.key_password,913cert_file=self.cert_file,914cert_reqs=self.cert_reqs,915ca_certs=self.ca_certs,916ca_cert_dir=self.ca_cert_dir,917assert_hostname=self.assert_hostname,918assert_fingerprint=self.assert_fingerprint,919)920conn.ssl_version = self.ssl_version921return conn922923def _prepare_proxy(self, conn):924"""925Establish tunnel connection early, because otherwise httplib926would improperly set Host: header to proxy's IP:port.927"""928conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)929conn.connect()930931def _new_conn(self):932"""933Return a fresh :class:`httplib.HTTPSConnection`.934"""935self.num_connections += 1936log.debug(937"Starting new HTTPS connection (%d): %s:%s",938self.num_connections,939self.host,940self.port or "443",941)942943if not self.ConnectionCls or self.ConnectionCls is DummyConnection:944raise SSLError(945"Can't connect to HTTPS URL because the SSL module is not available."946)947948actual_host = self.host949actual_port = self.port950if self.proxy is not None:951actual_host = self.proxy.host952actual_port = self.proxy.port953954conn = self.ConnectionCls(955host=actual_host,956port=actual_port,957timeout=self.timeout.connect_timeout,958strict=self.strict,959cert_file=self.cert_file,960key_file=self.key_file,961key_password=self.key_password,962**self.conn_kw963)964965return self._prepare_conn(conn)966967def _validate_conn(self, conn):968"""969Called right before a request is made, after the socket is created.970"""971super(HTTPSConnectionPool, self)._validate_conn(conn)972973# Force connect early to allow us to validate the connection.974if not getattr(conn, "sock", None): # AppEngine might not have `.sock`975conn.connect()976977if not conn.is_verified:978warnings.warn(979(980"Unverified HTTPS request is being made to host '%s'. "981"Adding certificate verification is strongly advised. See: "982"https://urllib3.readthedocs.io/en/latest/advanced-usage.html"983"#ssl-warnings" % conn.host984),985InsecureRequestWarning,986)987988989def connection_from_url(url, **kw):990"""991Given a url, return an :class:`.ConnectionPool` instance of its host.992993This is a shortcut for not having to parse out the scheme, host, and port994of the url before creating an :class:`.ConnectionPool` instance.995996:param url:997Absolute URL string that must include the scheme. Port is optional.998999:param \\**kw:1000Passes additional parameters to the constructor of the appropriate1001:class:`.ConnectionPool`. Useful for specifying things like1002timeout, maxsize, headers, etc.10031004Example::10051006>>> conn = connection_from_url('http://google.com/')1007>>> r = conn.request('GET', '/')1008"""1009scheme, host, port = get_host(url)1010port = port or port_by_scheme.get(scheme, 80)1011if scheme == "https":1012return HTTPSConnectionPool(host, port=port, **kw)1013else:1014return HTTPConnectionPool(host, port=port, **kw)101510161017def _normalize_host(host, scheme):1018"""1019Normalize hosts for comparisons and use with sockets.1020"""10211022host = normalize_host(host, scheme)10231024# httplib doesn't like it when we include brackets in IPv6 addresses1025# Specifically, if we include brackets but also pass the port then1026# httplib crazily doubles up the square brackets on the Host header.1027# Instead, we need to make sure we never pass ``None`` as the port.1028# However, for backward compatibility reasons we can't actually1029# *assert* that. See http://bugs.python.org/issue285391030if host.startswith("[") and host.endswith("]"):1031host = host[1:-1]1032return host103310341035