adapters.py 27 KB

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