poolmanager.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. from __future__ import annotations
  2. import functools
  3. import logging
  4. import typing
  5. import warnings
  6. from types import TracebackType
  7. from urllib.parse import urljoin
  8. from ._collections import HTTPHeaderDict, RecentlyUsedContainer
  9. from ._request_methods import RequestMethods
  10. from .connection import ProxyConfig
  11. from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme
  12. from .exceptions import (
  13. LocationValueError,
  14. MaxRetryError,
  15. ProxySchemeUnknown,
  16. URLSchemeUnknown,
  17. )
  18. from .response import BaseHTTPResponse
  19. from .util.connection import _TYPE_SOCKET_OPTIONS
  20. from .util.proxy import connection_requires_http_tunnel
  21. from .util.retry import Retry
  22. from .util.timeout import Timeout
  23. from .util.url import Url, parse_url
  24. if typing.TYPE_CHECKING:
  25. import ssl
  26. from typing_extensions import Self
  27. __all__ = ["PoolManager", "ProxyManager", "proxy_from_url"]
  28. log = logging.getLogger(__name__)
  29. SSL_KEYWORDS = (
  30. "key_file",
  31. "cert_file",
  32. "cert_reqs",
  33. "ca_certs",
  34. "ca_cert_data",
  35. "ssl_version",
  36. "ssl_minimum_version",
  37. "ssl_maximum_version",
  38. "ca_cert_dir",
  39. "ssl_context",
  40. "key_password",
  41. "server_hostname",
  42. "assert_hostname",
  43. "assert_fingerprint",
  44. )
  45. # Default value for `blocksize` - a new parameter introduced to
  46. # http.client.HTTPConnection & http.client.HTTPSConnection in Python 3.7
  47. _DEFAULT_BLOCKSIZE = 16384
  48. class PoolKey(typing.NamedTuple):
  49. """
  50. All known keyword arguments that could be provided to the pool manager, its
  51. pools, or the underlying connections.
  52. All custom key schemes should include the fields in this key at a minimum.
  53. """
  54. key_scheme: str
  55. key_host: str
  56. key_port: int | None
  57. key_timeout: Timeout | float | int | None
  58. key_retries: Retry | bool | int | None
  59. key_block: bool | None
  60. key_source_address: tuple[str, int] | None
  61. key_key_file: str | None
  62. key_key_password: str | None
  63. key_cert_file: str | None
  64. key_cert_reqs: str | None
  65. key_ca_certs: str | None
  66. key_ca_cert_data: str | bytes | None
  67. key_ssl_version: int | str | None
  68. key_ssl_minimum_version: ssl.TLSVersion | None
  69. key_ssl_maximum_version: ssl.TLSVersion | None
  70. key_ca_cert_dir: str | None
  71. key_ssl_context: ssl.SSLContext | None
  72. key_maxsize: int | None
  73. key_headers: frozenset[tuple[str, str]] | None
  74. key__proxy: Url | None
  75. key__proxy_headers: frozenset[tuple[str, str]] | None
  76. key__proxy_config: ProxyConfig | None
  77. key_socket_options: _TYPE_SOCKET_OPTIONS | None
  78. key__socks_options: frozenset[tuple[str, str]] | None
  79. key_assert_hostname: bool | str | None
  80. key_assert_fingerprint: str | None
  81. key_server_hostname: str | None
  82. key_blocksize: int | None
  83. def _default_key_normalizer(
  84. key_class: type[PoolKey], request_context: dict[str, typing.Any]
  85. ) -> PoolKey:
  86. """
  87. Create a pool key out of a request context dictionary.
  88. According to RFC 3986, both the scheme and host are case-insensitive.
  89. Therefore, this function normalizes both before constructing the pool
  90. key for an HTTPS request. If you wish to change this behaviour, provide
  91. alternate callables to ``key_fn_by_scheme``.
  92. :param key_class:
  93. The class to use when constructing the key. This should be a namedtuple
  94. with the ``scheme`` and ``host`` keys at a minimum.
  95. :type key_class: namedtuple
  96. :param request_context:
  97. A dictionary-like object that contain the context for a request.
  98. :type request_context: dict
  99. :return: A namedtuple that can be used as a connection pool key.
  100. :rtype: PoolKey
  101. """
  102. # Since we mutate the dictionary, make a copy first
  103. context = request_context.copy()
  104. context["scheme"] = context["scheme"].lower()
  105. context["host"] = context["host"].lower()
  106. # These are both dictionaries and need to be transformed into frozensets
  107. for key in ("headers", "_proxy_headers", "_socks_options"):
  108. if key in context and context[key] is not None:
  109. context[key] = frozenset(context[key].items())
  110. # The socket_options key may be a list and needs to be transformed into a
  111. # tuple.
  112. socket_opts = context.get("socket_options")
  113. if socket_opts is not None:
  114. context["socket_options"] = tuple(socket_opts)
  115. # Map the kwargs to the names in the namedtuple - this is necessary since
  116. # namedtuples can't have fields starting with '_'.
  117. for key in list(context.keys()):
  118. context["key_" + key] = context.pop(key)
  119. # Default to ``None`` for keys missing from the context
  120. for field in key_class._fields:
  121. if field not in context:
  122. context[field] = None
  123. # Default key_blocksize to _DEFAULT_BLOCKSIZE if missing from the context
  124. if context.get("key_blocksize") is None:
  125. context["key_blocksize"] = _DEFAULT_BLOCKSIZE
  126. return key_class(**context)
  127. #: A dictionary that maps a scheme to a callable that creates a pool key.
  128. #: This can be used to alter the way pool keys are constructed, if desired.
  129. #: Each PoolManager makes a copy of this dictionary so they can be configured
  130. #: globally here, or individually on the instance.
  131. key_fn_by_scheme = {
  132. "http": functools.partial(_default_key_normalizer, PoolKey),
  133. "https": functools.partial(_default_key_normalizer, PoolKey),
  134. }
  135. pool_classes_by_scheme = {"http": HTTPConnectionPool, "https": HTTPSConnectionPool}
  136. class PoolManager(RequestMethods):
  137. """
  138. Allows for arbitrary requests while transparently keeping track of
  139. necessary connection pools for you.
  140. :param num_pools:
  141. Number of connection pools to cache before discarding the least
  142. recently used pool.
  143. :param headers:
  144. Headers to include with all requests, unless other headers are given
  145. explicitly.
  146. :param \\**connection_pool_kw:
  147. Additional parameters are used to create fresh
  148. :class:`urllib3.connectionpool.ConnectionPool` instances.
  149. Example:
  150. .. code-block:: python
  151. import urllib3
  152. http = urllib3.PoolManager(num_pools=2)
  153. resp1 = http.request("GET", "https://google.com/")
  154. resp2 = http.request("GET", "https://google.com/mail")
  155. resp3 = http.request("GET", "https://yahoo.com/")
  156. print(len(http.pools))
  157. # 2
  158. """
  159. proxy: Url | None = None
  160. proxy_config: ProxyConfig | None = None
  161. def __init__(
  162. self,
  163. num_pools: int = 10,
  164. headers: typing.Mapping[str, str] | None = None,
  165. **connection_pool_kw: typing.Any,
  166. ) -> None:
  167. super().__init__(headers)
  168. # PoolManager handles redirects itself in PoolManager.urlopen().
  169. # It always passes redirect=False to the underlying connection pool to
  170. # suppress per-pool redirect handling. If the user supplied a non-Retry
  171. # value (int/bool/etc) for retries and we let the pool normalize it
  172. # while redirect=False, the resulting Retry object would have redirect
  173. # handling disabled, which can interfere with PoolManager's own
  174. # redirect logic. Normalize here so redirects remain governed solely by
  175. # PoolManager logic.
  176. if "retries" in connection_pool_kw:
  177. retries = connection_pool_kw["retries"]
  178. if not isinstance(retries, Retry):
  179. retries = Retry.from_int(retries)
  180. connection_pool_kw = connection_pool_kw.copy()
  181. connection_pool_kw["retries"] = retries
  182. self.connection_pool_kw = connection_pool_kw
  183. self.pools: RecentlyUsedContainer[PoolKey, HTTPConnectionPool]
  184. self.pools = RecentlyUsedContainer(num_pools)
  185. # Locally set the pool classes and keys so other PoolManagers can
  186. # override them.
  187. self.pool_classes_by_scheme = pool_classes_by_scheme
  188. self.key_fn_by_scheme = key_fn_by_scheme.copy()
  189. def __enter__(self) -> Self:
  190. return self
  191. def __exit__(
  192. self,
  193. exc_type: type[BaseException] | None,
  194. exc_val: BaseException | None,
  195. exc_tb: TracebackType | None,
  196. ) -> typing.Literal[False]:
  197. self.clear()
  198. # Return False to re-raise any potential exceptions
  199. return False
  200. def _new_pool(
  201. self,
  202. scheme: str,
  203. host: str,
  204. port: int,
  205. request_context: dict[str, typing.Any] | None = None,
  206. ) -> HTTPConnectionPool:
  207. """
  208. Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and
  209. any additional pool keyword arguments.
  210. If ``request_context`` is provided, it is provided as keyword arguments
  211. to the pool class used. This method is used to actually create the
  212. connection pools handed out by :meth:`connection_from_url` and
  213. companion methods. It is intended to be overridden for customization.
  214. """
  215. pool_cls: type[HTTPConnectionPool] = self.pool_classes_by_scheme[scheme]
  216. if request_context is None:
  217. request_context = self.connection_pool_kw.copy()
  218. # Default blocksize to _DEFAULT_BLOCKSIZE if missing or explicitly
  219. # set to 'None' in the request_context.
  220. if request_context.get("blocksize") is None:
  221. request_context["blocksize"] = _DEFAULT_BLOCKSIZE
  222. # Although the context has everything necessary to create the pool,
  223. # this function has historically only used the scheme, host, and port
  224. # in the positional args. When an API change is acceptable these can
  225. # be removed.
  226. for key in ("scheme", "host", "port"):
  227. request_context.pop(key, None)
  228. if scheme == "http":
  229. for kw in SSL_KEYWORDS:
  230. request_context.pop(kw, None)
  231. return pool_cls(host, port, **request_context)
  232. def clear(self) -> None:
  233. """
  234. Empty our store of pools and direct them all to close.
  235. This will not affect in-flight connections, but they will not be
  236. re-used after completion.
  237. """
  238. self.pools.clear()
  239. def connection_from_host(
  240. self,
  241. host: str | None,
  242. port: int | None = None,
  243. scheme: str | None = "http",
  244. pool_kwargs: dict[str, typing.Any] | None = None,
  245. ) -> HTTPConnectionPool:
  246. """
  247. Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme.
  248. If ``port`` isn't given, it will be derived from the ``scheme`` using
  249. ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is
  250. provided, it is merged with the instance's ``connection_pool_kw``
  251. variable and used to create the new connection pool, if one is
  252. needed.
  253. """
  254. if not host:
  255. raise LocationValueError("No host specified.")
  256. request_context = self._merge_pool_kwargs(pool_kwargs)
  257. request_context["scheme"] = scheme or "http"
  258. if port is None:
  259. port = port_by_scheme.get(request_context["scheme"].lower(), 80)
  260. request_context["port"] = port
  261. request_context["host"] = host
  262. return self.connection_from_context(request_context)
  263. def connection_from_context(
  264. self, request_context: dict[str, typing.Any]
  265. ) -> HTTPConnectionPool:
  266. """
  267. Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context.
  268. ``request_context`` must at least contain the ``scheme`` key and its
  269. value must be a key in ``key_fn_by_scheme`` instance variable.
  270. """
  271. if "strict" in request_context:
  272. warnings.warn(
  273. "The 'strict' parameter is no longer needed on Python 3+. "
  274. "This will raise an error in urllib3 v3.0.",
  275. FutureWarning,
  276. )
  277. request_context.pop("strict")
  278. scheme = request_context["scheme"].lower()
  279. pool_key_constructor = self.key_fn_by_scheme.get(scheme)
  280. if not pool_key_constructor:
  281. raise URLSchemeUnknown(scheme)
  282. pool_key = pool_key_constructor(request_context)
  283. return self.connection_from_pool_key(pool_key, request_context=request_context)
  284. def connection_from_pool_key(
  285. self, pool_key: PoolKey, request_context: dict[str, typing.Any]
  286. ) -> HTTPConnectionPool:
  287. """
  288. Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key.
  289. ``pool_key`` should be a namedtuple that only contains immutable
  290. objects. At a minimum it must have the ``scheme``, ``host``, and
  291. ``port`` fields.
  292. """
  293. with self.pools.lock:
  294. # If the scheme, host, or port doesn't match existing open
  295. # connections, open a new ConnectionPool.
  296. pool = self.pools.get(pool_key)
  297. if pool:
  298. return pool
  299. # Make a fresh ConnectionPool of the desired type
  300. scheme = request_context["scheme"]
  301. host = request_context["host"]
  302. port = request_context["port"]
  303. pool = self._new_pool(scheme, host, port, request_context=request_context)
  304. self.pools[pool_key] = pool
  305. return pool
  306. def connection_from_url(
  307. self, url: str, pool_kwargs: dict[str, typing.Any] | None = None
  308. ) -> HTTPConnectionPool:
  309. """
  310. Similar to :func:`urllib3.connectionpool.connection_from_url`.
  311. If ``pool_kwargs`` is not provided and a new pool needs to be
  312. constructed, ``self.connection_pool_kw`` is used to initialize
  313. the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``
  314. is provided, it is used instead. Note that if a new pool does not
  315. need to be created for the request, the provided ``pool_kwargs`` are
  316. not used.
  317. """
  318. u = parse_url(url)
  319. return self.connection_from_host(
  320. u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs
  321. )
  322. def _merge_pool_kwargs(
  323. self, override: dict[str, typing.Any] | None
  324. ) -> dict[str, typing.Any]:
  325. """
  326. Merge a dictionary of override values for self.connection_pool_kw.
  327. This does not modify self.connection_pool_kw and returns a new dict.
  328. Any keys in the override dictionary with a value of ``None`` are
  329. removed from the merged dictionary.
  330. """
  331. base_pool_kwargs = self.connection_pool_kw.copy()
  332. if override:
  333. for key, value in override.items():
  334. if value is None:
  335. try:
  336. del base_pool_kwargs[key]
  337. except KeyError:
  338. pass
  339. else:
  340. base_pool_kwargs[key] = value
  341. return base_pool_kwargs
  342. def _proxy_requires_url_absolute_form(self, parsed_url: Url) -> bool:
  343. """
  344. Indicates if the proxy requires the complete destination URL in the
  345. request. Normally this is only needed when not using an HTTP CONNECT
  346. tunnel.
  347. """
  348. if self.proxy is None:
  349. return False
  350. return not connection_requires_http_tunnel(
  351. self.proxy, self.proxy_config, parsed_url.scheme
  352. )
  353. def urlopen( # type: ignore[override]
  354. self, method: str, url: str, redirect: bool = True, **kw: typing.Any
  355. ) -> BaseHTTPResponse:
  356. """
  357. Same as :meth:`urllib3.HTTPConnectionPool.urlopen`
  358. with custom cross-host redirect logic and only sends the request-uri
  359. portion of the ``url``.
  360. The given ``url`` parameter must be absolute, such that an appropriate
  361. :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
  362. """
  363. u = parse_url(url)
  364. if u.scheme is None:
  365. warnings.warn(
  366. "URLs without a scheme (ie 'https://') are deprecated and will raise an error "
  367. "in urllib3 v3.0. To avoid this FutureWarning ensure all URLs "
  368. "start with 'https://' or 'http://'. Read more in this issue: "
  369. "https://github.com/urllib3/urllib3/issues/2920",
  370. category=FutureWarning,
  371. stacklevel=2,
  372. )
  373. conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
  374. kw["assert_same_host"] = False
  375. kw["redirect"] = False
  376. if "headers" not in kw:
  377. kw["headers"] = self.headers
  378. if self._proxy_requires_url_absolute_form(u):
  379. response = conn.urlopen(method, u._replace(fragment=None).url, **kw)
  380. else:
  381. response = conn.urlopen(method, u.request_uri, **kw)
  382. redirect_location = redirect and response.get_redirect_location()
  383. if not redirect_location:
  384. return response
  385. # Support relative URLs for redirecting.
  386. redirect_location = urljoin(url, redirect_location)
  387. if response.status == 303:
  388. # Change the method according to RFC 9110, Section 15.4.4.
  389. method = "GET"
  390. # And lose the body not to transfer anything sensitive.
  391. kw["body"] = None
  392. # The body is gone, so the state that describes it has to go too:
  393. # there is nothing left to frame with chunked transfer encoding,
  394. # and nothing left to rewind.
  395. kw["chunked"] = False
  396. kw["body_pos"] = None
  397. kw["headers"] = HTTPHeaderDict(kw["headers"])._prepare_for_method_change()
  398. retries = kw.get("retries", response.retries)
  399. if not isinstance(retries, Retry):
  400. retries = Retry.from_int(retries, redirect=redirect)
  401. # Strip headers marked as unsafe to forward to the redirected location.
  402. # Check remove_headers_on_redirect to avoid a potential network call within
  403. # conn.is_same_host() which may use socket.gethostbyname() in the future.
  404. if retries.remove_headers_on_redirect and not conn.is_same_host(
  405. redirect_location
  406. ):
  407. new_headers = kw["headers"].copy()
  408. for header in kw["headers"]:
  409. if header.lower() in retries.remove_headers_on_redirect:
  410. new_headers.pop(header, None)
  411. kw["headers"] = new_headers
  412. try:
  413. retries = retries.increment(method, url, response=response, _pool=conn)
  414. except MaxRetryError:
  415. if retries.raise_on_redirect:
  416. response.drain_conn()
  417. raise
  418. return response
  419. kw["retries"] = retries
  420. kw["redirect"] = redirect
  421. log.info("Redirecting %s -> %s", url, redirect_location)
  422. response.drain_conn()
  423. return self.urlopen(method, redirect_location, **kw)
  424. class ProxyManager(PoolManager):
  425. """
  426. Behaves just like :class:`PoolManager`, but sends all requests through
  427. the defined proxy, using the CONNECT method for HTTPS URLs.
  428. :param proxy_url:
  429. The URL of the proxy to be used.
  430. :param proxy_headers:
  431. A dictionary containing headers that will be sent to the proxy. In case
  432. of HTTP they are being sent with each request, while in the
  433. HTTPS/CONNECT case they are sent only once. Could be used for proxy
  434. authentication.
  435. :param proxy_ssl_context:
  436. The proxy SSL context is used to establish the TLS connection to the
  437. proxy when using HTTPS proxies.
  438. :param use_forwarding_for_https:
  439. (Defaults to False) If set to True will forward requests to the HTTPS
  440. proxy to be made on behalf of the client instead of creating a TLS
  441. tunnel via the CONNECT method. **Enabling this flag means that request
  442. and response headers and content will be visible from the HTTPS proxy**
  443. whereas tunneling keeps request and response headers and content
  444. private. IP address, target hostname, SNI, and port are always visible
  445. to an HTTPS proxy even when this flag is disabled.
  446. :param proxy_assert_hostname:
  447. The hostname of the certificate to verify against.
  448. :param proxy_assert_fingerprint:
  449. The fingerprint of the certificate to verify against.
  450. Example:
  451. .. code-block:: python
  452. import urllib3
  453. proxy = urllib3.ProxyManager("https://localhost:3128/")
  454. resp1 = proxy.request("GET", "http://google.com/")
  455. resp2 = proxy.request("GET", "http://httpbin.org/")
  456. # One pool was shared by both plain HTTP requests.
  457. print(len(proxy.pools))
  458. # 1
  459. resp3 = proxy.request("GET", "https://httpbin.org/")
  460. resp4 = proxy.request("GET", "https://twitter.com/")
  461. # A separate pool was added for each HTTPS target.
  462. print(len(proxy.pools))
  463. # 3
  464. """
  465. def __init__(
  466. self,
  467. proxy_url: str,
  468. num_pools: int = 10,
  469. headers: typing.Mapping[str, str] | None = None,
  470. proxy_headers: typing.Mapping[str, str] | None = None,
  471. proxy_ssl_context: ssl.SSLContext | None = None,
  472. use_forwarding_for_https: bool = False,
  473. proxy_assert_hostname: None | str | typing.Literal[False] = None,
  474. proxy_assert_fingerprint: str | None = None,
  475. **connection_pool_kw: typing.Any,
  476. ) -> None:
  477. if isinstance(proxy_url, HTTPConnectionPool):
  478. str_proxy_url = f"{proxy_url.scheme}://{proxy_url.host}:{proxy_url.port}"
  479. else:
  480. str_proxy_url = proxy_url
  481. proxy = parse_url(str_proxy_url)
  482. if proxy.scheme not in ("http", "https"):
  483. raise ProxySchemeUnknown(proxy.scheme)
  484. # Keep the deprecated ssl_context fallback on the manager for
  485. # compatibility, while passing only explicit proxy policy to connections.
  486. self.proxy_ssl_context = proxy_ssl_context
  487. if (
  488. use_forwarding_for_https
  489. and proxy.scheme == "https"
  490. and connection_pool_kw.get("ssl_context") is not None
  491. ):
  492. warnings.warn(
  493. "Passing ssl_context when use_forwarding_for_https=True is deprecated "
  494. "and will raise an error in urllib3 v3.0. "
  495. "Use proxy_ssl_context to configure the TLS connection to the proxy.",
  496. FutureWarning,
  497. stacklevel=2,
  498. )
  499. if self.proxy_ssl_context is None:
  500. self.proxy_ssl_context = connection_pool_kw.get("ssl_context")
  501. if proxy.port is None:
  502. port = port_by_scheme.get(proxy.scheme, 80)
  503. proxy = proxy._replace(port=port)
  504. self.proxy = proxy
  505. self.proxy_headers = proxy_headers or {}
  506. self.proxy_config = ProxyConfig(
  507. proxy_ssl_context,
  508. use_forwarding_for_https,
  509. proxy_assert_hostname,
  510. proxy_assert_fingerprint,
  511. )
  512. connection_pool_kw["_proxy"] = self.proxy
  513. connection_pool_kw["_proxy_headers"] = self.proxy_headers
  514. connection_pool_kw["_proxy_config"] = self.proxy_config
  515. super().__init__(num_pools, headers, **connection_pool_kw)
  516. def connection_from_host(
  517. self,
  518. host: str | None,
  519. port: int | None = None,
  520. scheme: str | None = "http",
  521. pool_kwargs: dict[str, typing.Any] | None = None,
  522. ) -> HTTPConnectionPool:
  523. if scheme == "https":
  524. return super().connection_from_host(
  525. host, port, scheme, pool_kwargs=pool_kwargs
  526. )
  527. return super().connection_from_host(
  528. self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs # type: ignore[union-attr]
  529. )
  530. def _set_proxy_headers(
  531. self, url: str, headers: typing.Mapping[str, str] | None = None
  532. ) -> typing.Mapping[str, str]:
  533. """
  534. Sets headers needed by proxies: specifically, the Accept and Host
  535. headers. Only sets headers not provided by the user.
  536. """
  537. headers_ = {"Accept": "*/*"}
  538. netloc = parse_url(url).netloc
  539. if netloc:
  540. headers_["Host"] = netloc
  541. if headers:
  542. headers_.update(headers)
  543. return headers_
  544. def urlopen( # type: ignore[override]
  545. self, method: str, url: str, redirect: bool = True, **kw: typing.Any
  546. ) -> BaseHTTPResponse:
  547. "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
  548. u = parse_url(url)
  549. if not connection_requires_http_tunnel(self.proxy, self.proxy_config, u.scheme):
  550. # For connections using HTTP CONNECT, httplib sets the necessary
  551. # headers on the CONNECT to the proxy. If we're not using CONNECT,
  552. # we'll definitely need to set 'Host' at the very least.
  553. headers = kw.get("headers", self.headers)
  554. kw["headers"] = self._set_proxy_headers(url, headers)
  555. return super().urlopen(method, url, redirect=redirect, **kw)
  556. def proxy_from_url(url: str, **kw: typing.Any) -> ProxyManager:
  557. return ProxyManager(proxy_url=url, **kw)