adapters.py 26 KB

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