adapters.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. """
  2. requests.adapters
  3. ~~~~~~~~~~~~~~~~~
  4. This module contains the transport adapters that Requests uses to define
  5. and maintain connections.
  6. """
  7. import os.path
  8. import socket # noqa: F401
  9. import typing
  10. import warnings
  11. from urllib3.exceptions import (
  12. ClosedPoolError,
  13. ConnectTimeoutError,
  14. LocationValueError,
  15. MaxRetryError,
  16. NewConnectionError,
  17. ProtocolError,
  18. ReadTimeoutError,
  19. ResponseError,
  20. )
  21. from urllib3.exceptions import HTTPError as _HTTPError
  22. from urllib3.exceptions import InvalidHeader as _InvalidHeader
  23. from urllib3.exceptions import ProxyError as _ProxyError
  24. from urllib3.exceptions import SSLError as _SSLError
  25. from urllib3.poolmanager import PoolManager, proxy_from_url
  26. from urllib3.util import Timeout as TimeoutSauce
  27. from urllib3.util import parse_url
  28. from urllib3.util.retry import Retry
  29. from .auth import _basic_auth_str
  30. from .compat import basestring, urlparse
  31. from .cookies import extract_cookies_to_jar
  32. from .exceptions import (
  33. ConnectionError,
  34. ConnectTimeout,
  35. InvalidHeader,
  36. InvalidProxyURL,
  37. InvalidSchema,
  38. InvalidURL,
  39. ProxyError,
  40. ReadTimeout,
  41. RetryError,
  42. SSLError,
  43. )
  44. from .models import Response
  45. from .structures import CaseInsensitiveDict
  46. from .utils import (
  47. DEFAULT_CA_BUNDLE_PATH,
  48. get_auth_from_url,
  49. get_encoding_from_headers,
  50. prepend_scheme_if_needed,
  51. select_proxy,
  52. urldefragauth,
  53. )
  54. try:
  55. from urllib3.contrib.socks import SOCKSProxyManager
  56. except ImportError:
  57. def SOCKSProxyManager(*args, **kwargs):
  58. raise InvalidSchema("Missing dependencies for SOCKS support.")
  59. if typing.TYPE_CHECKING:
  60. from .models import PreparedRequest
  61. DEFAULT_POOLBLOCK = False
  62. DEFAULT_POOLSIZE = 10
  63. DEFAULT_RETRIES = 0
  64. DEFAULT_POOL_TIMEOUT = None
  65. def _urllib3_request_context(
  66. request: "PreparedRequest",
  67. verify: "bool | str | None",
  68. client_cert: "tuple[str, str] | str | None",
  69. poolmanager: "PoolManager",
  70. ) -> "(dict[str, typing.Any], dict[str, typing.Any])":
  71. host_params = {}
  72. pool_kwargs = {}
  73. parsed_request_url = urlparse(request.url)
  74. scheme = parsed_request_url.scheme.lower()
  75. port = parsed_request_url.port
  76. cert_reqs = "CERT_REQUIRED"
  77. if verify is False:
  78. cert_reqs = "CERT_NONE"
  79. elif isinstance(verify, str):
  80. if not os.path.isdir(verify):
  81. pool_kwargs["ca_certs"] = verify
  82. else:
  83. pool_kwargs["ca_cert_dir"] = verify
  84. pool_kwargs["cert_reqs"] = cert_reqs
  85. if client_cert is not None:
  86. if isinstance(client_cert, tuple) and len(client_cert) == 2:
  87. pool_kwargs["cert_file"] = client_cert[0]
  88. pool_kwargs["key_file"] = client_cert[1]
  89. else:
  90. # According to our docs, we allow users to specify just the client
  91. # cert path
  92. pool_kwargs["cert_file"] = client_cert
  93. host_params = {
  94. "scheme": scheme,
  95. "host": parsed_request_url.hostname,
  96. "port": port,
  97. }
  98. return host_params, pool_kwargs
  99. class BaseAdapter:
  100. """The Base Transport Adapter"""
  101. def __init__(self):
  102. super().__init__()
  103. def send(
  104. self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None
  105. ):
  106. """Sends PreparedRequest object. Returns Response object.
  107. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
  108. :param stream: (optional) Whether to stream the request content.
  109. :param timeout: (optional) How long to wait for the server to send
  110. data before giving up, as a float, or a :ref:`(connect timeout,
  111. read timeout) <timeouts>` tuple.
  112. :type timeout: float or tuple
  113. :param verify: (optional) Either a boolean, in which case it controls whether we verify
  114. the server's TLS certificate, or a string, in which case it must be a path
  115. to a CA bundle to use
  116. :param cert: (optional) Any user-provided SSL certificate to be trusted.
  117. :param proxies: (optional) The proxies dictionary to apply to the request.
  118. """
  119. raise NotImplementedError
  120. def close(self):
  121. """Cleans up adapter specific items."""
  122. raise NotImplementedError
  123. class HTTPAdapter(BaseAdapter):
  124. """The built-in HTTP Adapter for urllib3.
  125. Provides a general-case interface for Requests sessions to contact HTTP and
  126. HTTPS urls by implementing the Transport Adapter interface. This class will
  127. usually be created by the :class:`Session <Session>` class under the
  128. covers.
  129. :param pool_connections: The number of urllib3 connection pools to cache.
  130. :param pool_maxsize: The maximum number of connections to save in the pool.
  131. :param max_retries: The maximum number of retries each connection
  132. should attempt. Note, this applies only to failed DNS lookups, socket
  133. connections and connection timeouts, never to requests where data has
  134. made it to the server. By default, Requests does not retry failed
  135. connections. If you need granular control over the conditions under
  136. which we retry a request, import urllib3's ``Retry`` class and pass
  137. that instead.
  138. :param pool_block: Whether the connection pool should block for connections.
  139. Usage::
  140. >>> import requests
  141. >>> s = requests.Session()
  142. >>> a = requests.adapters.HTTPAdapter(max_retries=3)
  143. >>> s.mount('http://', a)
  144. """
  145. __attrs__ = [
  146. "max_retries",
  147. "config",
  148. "_pool_connections",
  149. "_pool_maxsize",
  150. "_pool_block",
  151. ]
  152. def __init__(
  153. self,
  154. pool_connections=DEFAULT_POOLSIZE,
  155. pool_maxsize=DEFAULT_POOLSIZE,
  156. max_retries=DEFAULT_RETRIES,
  157. pool_block=DEFAULT_POOLBLOCK,
  158. ):
  159. if max_retries == DEFAULT_RETRIES:
  160. self.max_retries = Retry(0, read=False)
  161. else:
  162. self.max_retries = Retry.from_int(max_retries)
  163. self.config = {}
  164. self.proxy_manager = {}
  165. super().__init__()
  166. self._pool_connections = pool_connections
  167. self._pool_maxsize = pool_maxsize
  168. self._pool_block = pool_block
  169. self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)
  170. def __getstate__(self):
  171. return {attr: getattr(self, attr, None) for attr in self.__attrs__}
  172. def __setstate__(self, state):
  173. # Can't handle by adding 'proxy_manager' to self.__attrs__ because
  174. # self.poolmanager uses a lambda function, which isn't pickleable.
  175. self.proxy_manager = {}
  176. self.config = {}
  177. for attr, value in state.items():
  178. setattr(self, attr, value)
  179. self.init_poolmanager(
  180. self._pool_connections, self._pool_maxsize, block=self._pool_block
  181. )
  182. def init_poolmanager(
  183. self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs
  184. ):
  185. """Initializes a urllib3 PoolManager.
  186. This method should not be called from user code, and is only
  187. exposed for use when subclassing the
  188. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  189. :param connections: The number of urllib3 connection pools to cache.
  190. :param maxsize: The maximum number of connections to save in the pool.
  191. :param block: Block when no free connections are available.
  192. :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
  193. """
  194. # save these values for pickling
  195. self._pool_connections = connections
  196. self._pool_maxsize = maxsize
  197. self._pool_block = block
  198. self.poolmanager = PoolManager(
  199. num_pools=connections,
  200. maxsize=maxsize,
  201. block=block,
  202. **pool_kwargs,
  203. )
  204. def proxy_manager_for(self, proxy, **proxy_kwargs):
  205. """Return urllib3 ProxyManager for the given proxy.
  206. This method should not be called from user code, and is only
  207. exposed for use when subclassing the
  208. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  209. :param proxy: The proxy to return a urllib3 ProxyManager for.
  210. :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
  211. :returns: ProxyManager
  212. :rtype: urllib3.ProxyManager
  213. """
  214. if proxy in self.proxy_manager:
  215. manager = self.proxy_manager[proxy]
  216. elif proxy.lower().startswith("socks"):
  217. username, password = get_auth_from_url(proxy)
  218. manager = self.proxy_manager[proxy] = SOCKSProxyManager(
  219. proxy,
  220. username=username,
  221. password=password,
  222. num_pools=self._pool_connections,
  223. maxsize=self._pool_maxsize,
  224. block=self._pool_block,
  225. **proxy_kwargs,
  226. )
  227. else:
  228. proxy_headers = self.proxy_headers(proxy)
  229. manager = self.proxy_manager[proxy] = proxy_from_url(
  230. proxy,
  231. proxy_headers=proxy_headers,
  232. num_pools=self._pool_connections,
  233. maxsize=self._pool_maxsize,
  234. block=self._pool_block,
  235. **proxy_kwargs,
  236. )
  237. return manager
  238. def cert_verify(self, conn, url, verify, cert):
  239. """Verify a SSL certificate. This method should not be called from user
  240. code, and is only exposed for use when subclassing the
  241. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  242. :param conn: The urllib3 connection object associated with the cert.
  243. :param url: The requested URL.
  244. :param verify: Either a boolean, in which case it controls whether we verify
  245. the server's TLS certificate, or a string, in which case it must be a path
  246. to a CA bundle to use
  247. :param cert: The SSL certificate to verify.
  248. """
  249. if url.lower().startswith("https") and verify:
  250. cert_loc = None
  251. # Allow self-specified cert location.
  252. if verify is not True:
  253. cert_loc = verify
  254. if not cert_loc:
  255. cert_loc = DEFAULT_CA_BUNDLE_PATH
  256. if not cert_loc or not os.path.exists(cert_loc):
  257. raise OSError(
  258. f"Could not find a suitable TLS CA certificate bundle, "
  259. f"invalid path: {cert_loc}"
  260. )
  261. conn.cert_reqs = "CERT_REQUIRED"
  262. if not os.path.isdir(cert_loc):
  263. conn.ca_certs = cert_loc
  264. else:
  265. conn.ca_cert_dir = cert_loc
  266. else:
  267. conn.cert_reqs = "CERT_NONE"
  268. conn.ca_certs = None
  269. conn.ca_cert_dir = None
  270. if cert:
  271. if not isinstance(cert, basestring):
  272. conn.cert_file = cert[0]
  273. conn.key_file = cert[1]
  274. else:
  275. conn.cert_file = cert
  276. conn.key_file = None
  277. if conn.cert_file and not os.path.exists(conn.cert_file):
  278. raise OSError(
  279. f"Could not find the TLS certificate file, "
  280. f"invalid path: {conn.cert_file}"
  281. )
  282. if conn.key_file and not os.path.exists(conn.key_file):
  283. raise OSError(
  284. f"Could not find the TLS key file, invalid path: {conn.key_file}"
  285. )
  286. def build_response(self, req, resp):
  287. """Builds a :class:`Response <requests.Response>` object from a urllib3
  288. response. This should not be called from user code, and is only exposed
  289. for use when subclassing the
  290. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
  291. :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
  292. :param resp: The urllib3 response object.
  293. :rtype: requests.Response
  294. """
  295. response = Response()
  296. # Fallback to None if there's no status_code, for whatever reason.
  297. response.status_code = getattr(resp, "status", None)
  298. # Make headers case-insensitive.
  299. response.headers = CaseInsensitiveDict(getattr(resp, "headers", {}))
  300. # Set encoding.
  301. response.encoding = get_encoding_from_headers(response.headers)
  302. response.raw = resp
  303. response.reason = response.raw.reason
  304. if isinstance(req.url, bytes):
  305. response.url = req.url.decode("utf-8")
  306. else:
  307. response.url = req.url
  308. # Add new cookies from the server.
  309. extract_cookies_to_jar(response.cookies, req, resp)
  310. # Give the Response some context.
  311. response.request = req
  312. response.connection = self
  313. return response
  314. def build_connection_pool_key_attributes(self, request, verify, cert=None):
  315. """Build the PoolKey attributes used by urllib3 to return a connection.
  316. This looks at the PreparedRequest, the user-specified verify value,
  317. and the value of the cert parameter to determine what PoolKey values
  318. to use to select a connection from a given urllib3 Connection Pool.
  319. The SSL related pool key arguments are not consistently set. As of
  320. this writing, use the following to determine what keys may be in that
  321. dictionary:
  322. * If ``verify`` is ``True``, ``"ssl_context"`` will be set and will be the
  323. default Requests SSL Context
  324. * If ``verify`` is ``False``, ``"ssl_context"`` will not be set but
  325. ``"cert_reqs"`` will be set
  326. * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)
  327. ``"ca_certs"`` will be set if the string is not a directory recognized
  328. by :py:func:`os.path.isdir`, otherwise ``"ca_cert_dir"`` will be
  329. set.
  330. * If ``"cert"`` is specified, ``"cert_file"`` will always be set. If
  331. ``"cert"`` is a tuple with a second item, ``"key_file"`` will also
  332. be present
  333. To override these settings, one may subclass this class, call this
  334. method and use the above logic to change parameters as desired. For
  335. example, if one wishes to use a custom :py:class:`ssl.SSLContext` one
  336. must both set ``"ssl_context"`` and based on what else they require,
  337. alter the other keys to ensure the desired behaviour.
  338. :param request:
  339. The PreparedReqest being sent over the connection.
  340. :type request:
  341. :class:`~requests.models.PreparedRequest`
  342. :param verify:
  343. Either a boolean, in which case it controls whether
  344. we verify the server's TLS certificate, or a string, in which case it
  345. must be a path to a CA bundle to use.
  346. :param cert:
  347. (optional) Any user-provided SSL certificate for client
  348. authentication (a.k.a., mTLS). This may be a string (i.e., just
  349. the path to a file which holds both certificate and key) or a
  350. tuple of length 2 with the certificate file path and key file
  351. path.
  352. :returns:
  353. A tuple of two dictionaries. The first is the "host parameters"
  354. portion of the Pool Key including scheme, hostname, and port. The
  355. second is a dictionary of SSLContext related parameters.
  356. """
  357. return _urllib3_request_context(request, verify, cert, self.poolmanager)
  358. def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):
  359. """Returns a urllib3 connection for the given request and TLS settings.
  360. This should not be called from user code, and is only exposed for use
  361. when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  362. :param request:
  363. The :class:`PreparedRequest <PreparedRequest>` object to be sent
  364. over the connection.
  365. :param verify:
  366. Either a boolean, in which case it controls whether we verify the
  367. server's TLS certificate, or a string, in which case it must be a
  368. path to a CA bundle to use.
  369. :param proxies:
  370. (optional) The proxies dictionary to apply to the request.
  371. :param cert:
  372. (optional) Any user-provided SSL certificate to be used for client
  373. authentication (a.k.a., mTLS).
  374. :rtype:
  375. urllib3.ConnectionPool
  376. """
  377. proxy = select_proxy(request.url, proxies)
  378. try:
  379. host_params, pool_kwargs = self.build_connection_pool_key_attributes(
  380. request,
  381. verify,
  382. cert,
  383. )
  384. except ValueError as e:
  385. raise InvalidURL(e, request=request)
  386. if proxy:
  387. proxy = prepend_scheme_if_needed(proxy, "http")
  388. proxy_url = parse_url(proxy)
  389. if not proxy_url.host:
  390. raise InvalidProxyURL(
  391. "Please check proxy URL. It is malformed "
  392. "and could be missing the host."
  393. )
  394. proxy_manager = self.proxy_manager_for(proxy)
  395. conn = proxy_manager.connection_from_host(
  396. **host_params, pool_kwargs=pool_kwargs
  397. )
  398. else:
  399. # Only scheme should be lower case
  400. conn = self.poolmanager.connection_from_host(
  401. **host_params, pool_kwargs=pool_kwargs
  402. )
  403. return conn
  404. def get_connection(self, url, proxies=None):
  405. """DEPRECATED: Users should move to `get_connection_with_tls_context`
  406. for all subclasses of HTTPAdapter using Requests>=2.32.2.
  407. Returns a urllib3 connection for the given URL. This should not be
  408. called from user code, and is only exposed for use when subclassing the
  409. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  410. :param url: The URL to connect to.
  411. :param proxies: (optional) A Requests-style dictionary of proxies used on this request.
  412. :rtype: urllib3.ConnectionPool
  413. """
  414. warnings.warn(
  415. (
  416. "`get_connection` has been deprecated in favor of "
  417. "`get_connection_with_tls_context`. Custom HTTPAdapter subclasses "
  418. "will need to migrate for Requests>=2.32.2. Please see "
  419. "https://github.com/psf/requests/pull/6710 for more details."
  420. ),
  421. DeprecationWarning,
  422. )
  423. proxy = select_proxy(url, proxies)
  424. if proxy:
  425. proxy = prepend_scheme_if_needed(proxy, "http")
  426. proxy_url = parse_url(proxy)
  427. if not proxy_url.host:
  428. raise InvalidProxyURL(
  429. "Please check proxy URL. It is malformed "
  430. "and could be missing the host."
  431. )
  432. proxy_manager = self.proxy_manager_for(proxy)
  433. conn = proxy_manager.connection_from_url(url)
  434. else:
  435. # Only scheme should be lower case
  436. parsed = urlparse(url)
  437. url = parsed.geturl()
  438. conn = self.poolmanager.connection_from_url(url)
  439. return conn
  440. def close(self):
  441. """Disposes of any internal state.
  442. Currently, this closes the PoolManager and any active ProxyManager,
  443. which closes any pooled connections.
  444. """
  445. self.poolmanager.clear()
  446. for proxy in self.proxy_manager.values():
  447. proxy.clear()
  448. def request_url(self, request, proxies):
  449. """Obtain the url to use when making the final request.
  450. If the message is being sent through a HTTP proxy, the full URL has to
  451. be used. Otherwise, we should only use the path portion of the URL.
  452. This should not be called from user code, and is only exposed for use
  453. when subclassing the
  454. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  455. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
  456. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
  457. :rtype: str
  458. """
  459. proxy = select_proxy(request.url, proxies)
  460. scheme = urlparse(request.url).scheme
  461. is_proxied_http_request = proxy and scheme != "https"
  462. using_socks_proxy = False
  463. if proxy:
  464. proxy_scheme = urlparse(proxy).scheme.lower()
  465. using_socks_proxy = proxy_scheme.startswith("socks")
  466. url = request.path_url
  467. if url.startswith("//"): # Don't confuse urllib3
  468. url = f"/{url.lstrip('/')}"
  469. if is_proxied_http_request and not using_socks_proxy:
  470. url = urldefragauth(request.url)
  471. return url
  472. def add_headers(self, request, **kwargs):
  473. """Add any headers needed by the connection. As of v2.0 this does
  474. nothing by default, but is left for overriding by users that subclass
  475. the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  476. This should not be called from user code, and is only exposed for use
  477. when subclassing the
  478. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  479. :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.
  480. :param kwargs: The keyword arguments from the call to send().
  481. """
  482. pass
  483. def proxy_headers(self, proxy):
  484. """Returns a dictionary of the headers to add to any request sent
  485. through a proxy. This works with urllib3 magic to ensure that they are
  486. correctly sent to the proxy, rather than in a tunnelled request if
  487. CONNECT is being used.
  488. This should not be called from user code, and is only exposed for use
  489. when subclassing the
  490. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  491. :param proxy: The url of the proxy being used for this request.
  492. :rtype: dict
  493. """
  494. headers = {}
  495. username, password = get_auth_from_url(proxy)
  496. if username:
  497. headers["Proxy-Authorization"] = _basic_auth_str(username, password)
  498. return headers
  499. def send(
  500. self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None
  501. ):
  502. """Sends PreparedRequest object. Returns Response object.
  503. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
  504. :param stream: (optional) Whether to stream the request content.
  505. :param timeout: (optional) How long to wait for the server to send
  506. data before giving up, as a float, or a :ref:`(connect timeout,
  507. read timeout) <timeouts>` tuple.
  508. :type timeout: float or tuple or urllib3 Timeout object
  509. :param verify: (optional) Either a boolean, in which case it controls whether
  510. we verify the server's TLS certificate, or a string, in which case it
  511. must be a path to a CA bundle to use
  512. :param cert: (optional) Any user-provided SSL certificate to be trusted.
  513. :param proxies: (optional) The proxies dictionary to apply to the request.
  514. :rtype: requests.Response
  515. """
  516. try:
  517. conn = self.get_connection_with_tls_context(
  518. request, verify, proxies=proxies, cert=cert
  519. )
  520. except LocationValueError as e:
  521. raise InvalidURL(e, request=request)
  522. self.cert_verify(conn, request.url, verify, cert)
  523. url = self.request_url(request, proxies)
  524. self.add_headers(
  525. request,
  526. stream=stream,
  527. timeout=timeout,
  528. verify=verify,
  529. cert=cert,
  530. proxies=proxies,
  531. )
  532. chunked = not (request.body is None or "Content-Length" in request.headers)
  533. if isinstance(timeout, tuple):
  534. try:
  535. connect, read = timeout
  536. timeout = TimeoutSauce(connect=connect, read=read)
  537. except ValueError:
  538. raise ValueError(
  539. f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, "
  540. f"or a single float to set both timeouts to the same value."
  541. )
  542. elif isinstance(timeout, TimeoutSauce):
  543. pass
  544. else:
  545. timeout = TimeoutSauce(connect=timeout, read=timeout)
  546. try:
  547. resp = conn.urlopen(
  548. method=request.method,
  549. url=url,
  550. body=request.body,
  551. headers=request.headers,
  552. redirect=False,
  553. assert_same_host=False,
  554. preload_content=False,
  555. decode_content=False,
  556. retries=self.max_retries,
  557. timeout=timeout,
  558. chunked=chunked,
  559. )
  560. except (ProtocolError, OSError) as err:
  561. raise ConnectionError(err, request=request)
  562. except MaxRetryError as e:
  563. if isinstance(e.reason, ConnectTimeoutError):
  564. # TODO: Remove this in 3.0.0: see #2811
  565. if not isinstance(e.reason, NewConnectionError):
  566. raise ConnectTimeout(e, request=request)
  567. if isinstance(e.reason, ResponseError):
  568. raise RetryError(e, request=request)
  569. if isinstance(e.reason, _ProxyError):
  570. raise ProxyError(e, request=request)
  571. if isinstance(e.reason, _SSLError):
  572. # This branch is for urllib3 v1.22 and later.
  573. raise SSLError(e, request=request)
  574. raise ConnectionError(e, request=request)
  575. except ClosedPoolError as e:
  576. raise ConnectionError(e, request=request)
  577. except _ProxyError as e:
  578. raise ProxyError(e)
  579. except (_SSLError, _HTTPError) as e:
  580. if isinstance(e, _SSLError):
  581. # This branch is for urllib3 versions earlier than v1.22
  582. raise SSLError(e, request=request)
  583. elif isinstance(e, ReadTimeoutError):
  584. raise ReadTimeout(e, request=request)
  585. elif isinstance(e, _InvalidHeader):
  586. raise InvalidHeader(e, request=request)
  587. else:
  588. raise
  589. return self.build_response(request, resp)