1from __future__
import absolute_import
9from socket
import error
as SocketError
10from socket
import timeout
as SocketTimeout
12from .connection
import (
19 VerifiedHTTPSConnection,
22from .exceptions
import (
27 InsecureRequestWarning,
37from .packages
import six
39from .request
import RequestMethods
40from .response
import HTTPResponse
42from .
util.proxy import connection_requires_http_tunnel
49from .
util.url import Url, _encode_target
50from .
util.url import _normalize_host
as normalize_host
51from .
util.url import get_host, parse_url
70 Base class for all connection pools, such as
71 :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.
74 ConnectionPool.urlopen() does not normalize or percent-encode target URIs
75 which is useful if your target server doesn't support percent-encoded
91 return "%s(host=%r, port=%r)" % (type(self).__name__, self.
host, self.
port)
103 Close all pooled connections and disable the pool.
114 Thread-safe connection pool for one host.
117 Host used for this HTTP Connection (e.g. "localhost"), passed into
118 :class:`http.client.HTTPConnection`.
121 Port used for this HTTP Connection (None is equivalent to 80), passed
122 into :class:`http.client.HTTPConnection`.
125 Causes BadStatusLine to be raised if the status line can't be parsed
126 as a valid HTTP/1.0 or 1.1 status line, passed into
127 :class:`http.client.HTTPConnection`.
130 Only works in Python 2. This parameter is ignored in Python 3.
133 Socket timeout in seconds for each individual connection. This can
134 be a float or integer, which sets the timeout for the HTTP request,
135 or an instance of :class:`urllib3.util.Timeout` which gives you more
136 fine-grained control over request timeouts. After the constructor has
137 been parsed, this is always a `urllib3.util.Timeout` object.
140 Number of connections to save that can be reused. More than 1 is useful
141 in multithreaded situations. If ``block`` is set to False, more
142 connections will be created but they will not be saved once they've
146 If set to True, no more than ``maxsize`` connections will be used at
147 a time. When no free connections are available, the call will block
148 until a connection has been released. This is a useful side effect for
149 particular multithreaded situations where one does not want to use more
150 than maxsize connections per host to prevent flooding.
153 Headers to include with all requests, unless other headers are given
157 Retry configuration to use by default with requests in this pool.
160 Parsed proxy URL, should not be used directly, instead, see
161 :class:`urllib3.ProxyManager`
163 :param _proxy_headers:
164 A dictionary with proxy headers, should not be used directly,
165 instead, see :class:`urllib3.ProxyManager`
168 Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,
169 :class:`urllib3.connection.HTTPSConnection` instances.
173 ConnectionCls = HTTPConnection
174 ResponseCls = HTTPResponse
181 timeout=Timeout.DEFAULT_TIMEOUT,
225 self.
conn_kw.setdefault(
"socket_options", [])
242 Return a fresh :class:`HTTPConnection`.
246 "Starting new HTTP connection (%d): %s:%s",
255 timeout=self.
timeout.connect_timeout,
263 Get a connection. Will return a pooled connection if one is available.
265 If no connections are available and :prop:`.block` is ``False``, then a
266 fresh connection is returned.
269 Seconds to wait before giving up and raising
270 :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and
271 :prop:`.block` is ``True``.
275 conn = self.
pool.get(block=self.
block, timeout=timeout)
277 except AttributeError:
284 "Pool reached maximum size and no more connections are allowed.",
289 if conn
and is_connection_dropped(conn):
292 if getattr(conn,
"auto_open", 1) == 0:
302 Put a connection back into the pool.
305 Connection object for the current host and port as returned by
306 :meth:`._new_conn` or :meth:`._get_conn`.
308 If the pool is already full, the connection is closed and discarded
309 because we exceeded maxsize. If connections are discarded frequently,
310 then maxsize should be increased.
312 If the pool is closed, then the connection will be closed and discarded.
315 self.
pool.put(conn, block=
False)
317 except AttributeError:
323 "Connection pool is full, discarding connection: %s. Connection pool size: %s",
333 Called right before a request is made, after the socket is created.
342 """Helper that always returns a :class:`urllib3.util.Timeout`"""
343 if timeout
is _Default:
344 return self.timeout.clone()
354 """Is the error actually a timeout? Will raise a ReadTimeout or pass"""
358 self, url,
"Read timed out. (read timeout=%s)" % timeout_value
365 self, url,
"Read timed out. (read timeout=%s)" % timeout_value
371 if "timed out" in str(err)
or "did not complete (read)" in str(
375 self, url,
"Read timed out. (read timeout=%s)" % timeout_value
379 self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw
382 Perform a request on a given urllib connection object taken from our
386 a connection from one of our connection pools
389 Socket timeout in seconds for the request. This can be a
390 float or integer, which will set the same timeout value for
391 the socket connect and the socket read, or an instance of
392 :class:`urllib3.util.Timeout`, which gives you more fine-grained
393 control over your timeouts.
404 except (SocketTimeout, BaseSSLError)
as e:
420 except BrokenPipeError:
438 if getattr(conn,
"sock",
None):
444 if read_timeout == 0:
446 self, url,
"Read timed out. (read timeout=%s)" % read_timeout
462 except BaseException
as e:
467 except (SocketTimeout, BaseSSLError, SocketError)
as e:
472 http_version =
getattr(conn,
"_http_vsn_str",
"HTTP/?")
474 '%s://%s:%s "%s %s %s" %s %s',
487 except (HeaderParsingError, TypeError)
as hpe:
489 "Failed to parse headers (url=%s): %s",
495 return httplib_response
502 Close all pooled connections and disable the pool.
504 if self.
pool is None:
507 old_pool, self.
pool = self.
pool,
None
514 Check if the given ``url`` is a member of the same host as this
521 scheme, host, port = get_host(url)
523 host = _normalize_host(host, scheme=scheme)
541 assert_same_host=True,
550 Get a connection from the pool and perform an HTTP request. This is the
551 lowest level call for making a request, so you'll need to specify all
556 More commonly, it's appropriate to use a convenience method provided
557 by :class:`.RequestMethods`, such as :meth:`request`.
561 `release_conn` will only behave as expected if
562 `preload_content=False` because we want to make
563 `preload_content=False` the default behaviour someday soon without
564 breaking backwards compatibility.
567 HTTP request method (such as GET, POST, PUT, etc.)
570 The URL to perform the request on.
573 Data to send in the request body, either :class:`str`, :class:`bytes`,
574 an iterable of :class:`str`/:class:`bytes`, or a file-like object.
577 Dictionary of custom headers to send, such as User-Agent,
578 If-None-Match, etc. If None, pool headers are used. If provided,
579 these headers completely replace any pool-specific headers.
582 Configure the number of retries to allow before raising a
583 :class:`~urllib3.exceptions.MaxRetryError` exception.
585 Pass ``None`` to retry until you receive a response. Pass a
586 :class:`~urllib3.util.retry.Retry` object for fine-grained control
587 over different types of retries.
588 Pass an integer number to retry connection errors that many times,
589 but no other types of errors. Pass zero to never retry.
591 If ``False``, then retries are disabled and any exception is raised
592 immediately. Also, instead of raising a MaxRetryError on redirects,
593 the redirect response will be returned.
595 :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
598 If True, automatically handle redirects (status codes 301, 302,
599 303, 307, 308). Each redirect counts as a retry. Disabling retries
600 will disable redirect, too.
602 :param assert_same_host:
603 If ``True``, will make sure that the host of the pool requests is
604 consistent else will raise HostChangedError. When ``False``, you can
605 use the pool on an HTTP proxy and request foreign hosts.
608 If specified, overrides the default timeout for this one
609 request. It may be a float (in seconds) or an instance of
610 :class:`urllib3.util.Timeout`.
613 If set and the pool is set to block=True, then this method will
614 block for ``pool_timeout`` seconds and raise EmptyPoolError if no
615 connection is available within the time period.
618 If False, then the urlopen call will not release the connection
619 back into the pool once a response is received (but will release if
620 you read the entire contents of the response such as when
621 `preload_content=True`). This is useful if you're not preloading
622 the response's content immediately. You will need to call
623 ``r.release_conn()`` on the response ``r`` to return the connection
624 back into the pool. If None, it takes the value of
625 ``response_kw.get('preload_content', True)``.
628 If True, urllib3 will send the body using chunked transfer
629 encoding. Otherwise, urllib3 will send the body using the standard
630 content-length form. Defaults to False.
633 Position to seek to in file-like body in the event of a retry or
634 redirect. Typically this won't need to be set because urllib3 will
635 auto-populate the value when needed.
637 :param \\**response_kw:
638 Additional parameters are passed to
639 :meth:`urllib3.response.HTTPResponse.from_httplib`
642 parsed_url = parse_url(url)
651 if release_conn
is None:
675 release_this_conn = release_conn
677 http_tunnel_required = connection_requires_http_tunnel(
684 if not http_tunnel_required:
698 body_pos = set_file_position(body, body_pos)
703 conn = self.
_get_conn(timeout=pool_timeout)
707 is_new_proxy_conn = self.
proxy is not None and not getattr(
710 if is_new_proxy_conn
and http_tunnel_required:
728 response_conn = conn
if not release_conn
else None
731 response_kw[
"request_method"] = method
737 connection=response_conn,
745 except EmptyPoolError:
748 release_this_conn =
False
768 message =
" ".join(
re.split(
"[^a-z]", str(ssl_error).
lower()))
770 "wrong version number" in message
or "unknown protocol" in message
785 "Your proxy appears to only use HTTP and not HTTPS, "
786 "try changing your proxy URL to be HTTP. See: "
787 "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"
788 "#https-proxy-error-http-proxy",
791 elif isinstance(e, (BaseSSLError, CertificateError)):
795 elif isinstance(e, (SocketError, HTTPException)):
799 method, url, error=e, _pool=self, _stacktrace=
sys.exc_info()[2]
813 release_this_conn =
True
815 if release_this_conn:
824 "Retrying (%r) after connection broken by '%r': %s", retries, err, url
835 pool_timeout=pool_timeout,
836 release_conn=release_conn,
844 if redirect_location:
850 except MaxRetryError:
858 log.debug(
"Redirecting %s -> %s", url, redirect_location)
866 assert_same_host=assert_same_host,
868 pool_timeout=pool_timeout,
869 release_conn=release_conn,
880 except MaxRetryError:
896 assert_same_host=assert_same_host,
898 pool_timeout=pool_timeout,
899 release_conn=release_conn,
910 Same as :class:`.HTTPConnectionPool`, but HTTPS.
912 :class:`.HTTPSConnection` uses one of ``assert_fingerprint``,
913 ``assert_hostname`` and ``host`` in this order to verify connections.
914 If ``assert_hostname`` is False, no verification is done.
916 The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``,
917 ``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl`
918 is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade
919 the connection socket into an SSL socket.
923 ConnectionCls = HTTPSConnection
930 timeout=Timeout.DEFAULT_TIMEOUT,
943 assert_hostname=None,
944 assert_fingerprint=None,
976 Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
977 and establish the tunnel if proxy is used.
996 Establishes a tunnel connection through HTTP CONNECT.
998 Tunnel connection is established early because otherwise httplib would
999 improperly set Host: header to proxy's IP:port.
1004 if self.
proxy.scheme ==
"https":
1011 Return a fresh :class:`http.client.HTTPSConnection`.
1015 "Starting new HTTPS connection (%d): %s:%s",
1023 "Can't connect to HTTPS URL because the SSL module is not available."
1028 if self.
proxy is not None:
1029 actual_host = self.
proxy.host
1030 actual_port = self.
proxy.port
1035 timeout=self.
timeout.connect_timeout,
1047 Called right before a request is made, after the socket is created.
1052 if not getattr(conn,
"sock",
None):
1058 "Unverified HTTPS request is being made to host '%s'. "
1059 "Adding certificate verification is strongly advised. See: "
1060 "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"
1063 InsecureRequestWarning,
1066 if getattr(conn,
"proxy_is_verified",
None)
is False:
1069 "Unverified HTTPS connection done to an HTTPS proxy. "
1070 "Adding certificate verification is strongly advised. See: "
1071 "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"
1074 InsecureRequestWarning,
1078def connection_from_url(url, **kw):
1080 Given a url, return an :class:`.ConnectionPool` instance of its host.
1082 This is a shortcut for not having to parse out the scheme, host, and port
1083 of the url before creating an :class:`.ConnectionPool` instance.
1086 Absolute URL string that must include the scheme. Port is optional.
1089 Passes additional parameters to the constructor of the appropriate
1090 :class:`.ConnectionPool`. Useful for specifying things like
1091 timeout, maxsize, headers, etc.
1095 >>> conn = connection_from_url('http://google.com/')
1096 >>> r = conn.request('GET', '/')
1098 scheme, host, port = get_host(url)
1100 if scheme ==
"https":
1106def _normalize_host(host, scheme):
1108 Normalize hosts for comparisons and use with sockets.
1125 """Drains a queue of connections and closes each one."""
__init__(self, host, port=None)
__exit__(self, exc_type, exc_val, exc_tb)
_absolute_url(self, path)
_make_request(self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw)
urlopen(self, method, url, body=None, headers=None, retries=None, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, chunked=False, body_pos=None, **response_kw)
_validate_conn(self, conn)
_raise_timeout(self, err, url, timeout_value)
_get_conn(self, timeout=None)
_get_timeout(self, timeout)
_prepare_proxy(self, conn)
__init__(self, host, port=None, strict=False, timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False, headers=None, retries=None, _proxy=None, _proxy_headers=None, _proxy_config=None, **conn_kw)
_validate_conn(self, conn)
__init__(self, host, port=None, strict=False, timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False, headers=None, retries=None, _proxy=None, _proxy_headers=None, key_file=None, cert_file=None, cert_reqs=None, key_password=None, ca_certs=None, ssl_version=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None, **conn_kw)
_prepare_conn(self, conn)
_prepare_proxy(self, conn)
urlopen(self, method, url, body=None, headers=None, encode_multipart=True, multipart_boundary=None, **kw)
_close_pool_connections(pool)