sessions.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. """
  2. requests.sessions
  3. ~~~~~~~~~~~~~~~~~
  4. This module provides a Session object to manage and persist settings across
  5. requests (cookies, auth, proxies).
  6. """
  7. from __future__ import annotations
  8. import os
  9. import sys
  10. import time
  11. from collections import OrderedDict
  12. from collections.abc import Generator, Mapping, MutableMapping
  13. from datetime import timedelta
  14. from typing import TYPE_CHECKING, Any, cast
  15. from ._internal_utils import to_native_string
  16. from ._types import is_prepared as _is_prepared
  17. from .adapters import HTTPAdapter
  18. from .auth import _basic_auth_str # type: ignore[reportPrivateUsage]
  19. from .compat import cookielib, urljoin, urlparse
  20. from .cookies import (
  21. RequestsCookieJar,
  22. cookiejar_from_dict,
  23. extract_cookies_to_jar,
  24. merge_cookies,
  25. )
  26. from .exceptions import (
  27. ChunkedEncodingError,
  28. ContentDecodingError,
  29. InvalidSchema,
  30. TooManyRedirects,
  31. )
  32. from .hooks import default_hooks, dispatch_hook
  33. # formerly defined here, reexposed here for backward compatibility
  34. from .models import ( # noqa: F401
  35. DEFAULT_REDIRECT_LIMIT,
  36. REDIRECT_STATI, # type: ignore[reportUnusedImport]
  37. PreparedRequest,
  38. Request,
  39. Response,
  40. )
  41. from .status_codes import codes
  42. from .structures import CaseInsensitiveDict
  43. from .utils import ( # noqa: F401
  44. DEFAULT_PORTS,
  45. default_headers,
  46. get_auth_from_url,
  47. get_environ_proxies,
  48. get_netrc_auth,
  49. requote_uri,
  50. resolve_proxies,
  51. rewind_body,
  52. should_bypass_proxies, # type: ignore[reportUnusedImport] # re-export for external consumers
  53. to_key_val_list,
  54. )
  55. if TYPE_CHECKING:
  56. from http.cookiejar import CookieJar
  57. from typing_extensions import Self, Unpack
  58. from . import _types as _t
  59. from .adapters import BaseAdapter
  60. # Preferred clock, based on which one is more accurate on a given system.
  61. if sys.platform == "win32":
  62. preferred_clock = time.perf_counter
  63. else:
  64. preferred_clock = time.time
  65. def merge_setting(
  66. request_setting: Any, session_setting: Any, dict_class: type = OrderedDict
  67. ) -> Any:
  68. """Determines appropriate setting for a given request, taking into account
  69. the explicit setting on that request, and the setting in the session. If a
  70. setting is a dictionary, they will be merged together using `dict_class`
  71. """
  72. if session_setting is None:
  73. return request_setting
  74. if request_setting is None:
  75. return session_setting
  76. # Bypass if not a dictionary (e.g. verify)
  77. if not (
  78. isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)
  79. ):
  80. return request_setting
  81. merged_setting = dict_class(to_key_val_list(session_setting)) # type: ignore[arg-type] # isinstance narrows Any to Mapping[Unknown]
  82. merged_setting.update(to_key_val_list(request_setting)) # type: ignore[arg-type]
  83. # Remove keys that are set to None. Extract keys first to avoid altering
  84. # the dictionary during iteration.
  85. none_keys = [k for (k, v) in merged_setting.items() if v is None]
  86. for key in none_keys:
  87. del merged_setting[key]
  88. return merged_setting
  89. def merge_hooks(
  90. request_hooks: _t.HooksType,
  91. session_hooks: _t.HooksType,
  92. dict_class: type = OrderedDict,
  93. ) -> _t.HooksType:
  94. """Properly merges both requests and session hooks.
  95. This is necessary because when request_hooks == {'response': []}, the
  96. merge breaks Session hooks entirely.
  97. """
  98. if session_hooks is None or session_hooks.get("response") == []:
  99. return request_hooks
  100. if request_hooks is None or request_hooks.get("response") == []:
  101. return session_hooks
  102. return merge_setting(request_hooks, session_hooks, dict_class)
  103. class SessionRedirectMixin:
  104. max_redirects: int
  105. trust_env: bool
  106. cookies: RequestsCookieJar
  107. def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ...
  108. def get_redirect_target(self, resp: Response) -> str | None:
  109. """Receives a Response. Returns a redirect URI or ``None``"""
  110. # Due to the nature of how requests processes redirects this method will
  111. # be called at least once upon the original response and at least twice
  112. # on each subsequent redirect response (if any).
  113. # If a custom mixin is used to handle this logic, it may be advantageous
  114. # to cache the redirect location onto the response object as a private
  115. # attribute.
  116. if resp.is_redirect:
  117. location = resp.headers["location"]
  118. # Currently the underlying http module on py3 decode headers
  119. # in latin1, but empirical evidence suggests that latin1 is very
  120. # rarely used with non-ASCII characters in HTTP headers.
  121. # It is more likely to get UTF8 header rather than latin1.
  122. # This causes incorrect handling of UTF8 encoded location headers.
  123. # To solve this, we re-encode the location in latin1.
  124. location = location.encode("latin1")
  125. return to_native_string(location, "utf8")
  126. return None
  127. def should_strip_auth(self, old_url: str, new_url: str) -> bool:
  128. """Decide whether Authorization header should be removed when redirecting"""
  129. old_parsed = urlparse(old_url)
  130. new_parsed = urlparse(new_url)
  131. if old_parsed.hostname != new_parsed.hostname:
  132. return True
  133. # Special case: allow http -> https redirect when using the standard
  134. # ports. This isn't specified by RFC 7235, but is kept to avoid
  135. # breaking backwards compatibility with older versions of requests
  136. # that allowed any redirects on the same host.
  137. if (
  138. old_parsed.scheme == "http"
  139. and old_parsed.port in (80, None)
  140. and new_parsed.scheme == "https"
  141. and new_parsed.port in (443, None)
  142. ):
  143. return False
  144. # Handle default port usage corresponding to scheme.
  145. changed_port = old_parsed.port != new_parsed.port
  146. changed_scheme = old_parsed.scheme != new_parsed.scheme
  147. default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)
  148. if (
  149. not changed_scheme
  150. and old_parsed.port in default_port
  151. and new_parsed.port in default_port
  152. ):
  153. return False
  154. # Standard case: root URI must match
  155. return changed_port or changed_scheme
  156. def resolve_redirects(
  157. self,
  158. resp: Response,
  159. req: PreparedRequest,
  160. stream: bool = False,
  161. timeout: _t.TimeoutType = None,
  162. verify: _t.VerifyType = True,
  163. cert: _t.CertType = None,
  164. proxies: dict[str, str] | None = None,
  165. yield_requests: bool = False,
  166. **adapter_kwargs: Any,
  167. ) -> Generator[Response, None, None]:
  168. """Receives a Response. Returns a generator of Responses or Requests."""
  169. hist: list[Response] = [] # keep track of history
  170. url = self.get_redirect_target(resp)
  171. previous_fragment = urlparse(req.url).fragment
  172. while url:
  173. prepared_request = req.copy()
  174. # Update history and keep track of redirects.
  175. resp.history = hist[:]
  176. hist.append(resp)
  177. try:
  178. resp.content # Consume socket so it can be released
  179. except (ChunkedEncodingError, ContentDecodingError, RuntimeError):
  180. resp.raw.read(decode_content=False)
  181. if len(resp.history) >= self.max_redirects:
  182. raise TooManyRedirects(
  183. f"Exceeded {self.max_redirects} redirects.", response=resp
  184. )
  185. # Release the connection back into the pool.
  186. resp.close()
  187. # Handle redirection without scheme (see: RFC 1808 Section 4)
  188. if url.startswith("//"):
  189. parsed_rurl = urlparse(resp.url)
  190. url = ":".join([to_native_string(parsed_rurl.scheme), url])
  191. # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)
  192. parsed = urlparse(url)
  193. if parsed.fragment == "" and previous_fragment:
  194. parsed = parsed._replace(fragment=previous_fragment)
  195. elif parsed.fragment:
  196. previous_fragment = parsed.fragment
  197. url = parsed.geturl()
  198. # Facilitate relative 'location' headers, as allowed by RFC 7231.
  199. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
  200. # Compliant with RFC3986, we percent encode the url.
  201. if not parsed.netloc:
  202. url = urljoin(resp.url, requote_uri(url))
  203. else:
  204. url = requote_uri(url)
  205. prepared_request.url = to_native_string(url)
  206. self.rebuild_method(prepared_request, resp)
  207. # https://github.com/psf/requests/issues/1084
  208. if resp.status_code not in (
  209. codes.temporary_redirect,
  210. codes.permanent_redirect,
  211. ):
  212. # https://github.com/psf/requests/issues/3490
  213. purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding")
  214. for header in purged_headers:
  215. prepared_request.headers.pop(header, None)
  216. prepared_request.body = None
  217. headers = prepared_request.headers
  218. headers.pop("Cookie", None)
  219. # Extract any cookies sent on the response to the cookiejar
  220. # in the new request. Because we've mutated our copied prepared
  221. # request, use the old one that we haven't yet touched.
  222. cookie_jar = cast("CookieJar", prepared_request._cookies) # type: ignore[reportPrivateUsage]
  223. extract_cookies_to_jar(cookie_jar, req, resp.raw)
  224. merge_cookies(cookie_jar, self.cookies)
  225. prepared_request.prepare_cookies(cookie_jar)
  226. # Rebuild auth and proxy information.
  227. proxies = self.rebuild_proxies(prepared_request, proxies)
  228. self.rebuild_auth(prepared_request, resp)
  229. # A failed tell() sets `_body_position` to `object()`. This non-None
  230. # value ensures `rewindable` will be True, allowing us to raise an
  231. # UnrewindableBodyError, instead of hanging the connection.
  232. rewindable = prepared_request._body_position is not None and ( # type: ignore[reportPrivateUsage]
  233. "Content-Length" in headers or "Transfer-Encoding" in headers
  234. )
  235. # Attempt to rewind consumed file-like object.
  236. if rewindable:
  237. rewind_body(prepared_request)
  238. # Override the original request.
  239. req = prepared_request
  240. if yield_requests:
  241. yield req # type: ignore[misc] # Internal use only, returns PreparedRequest
  242. else:
  243. resp = self.send(
  244. req,
  245. stream=stream,
  246. timeout=timeout,
  247. verify=verify,
  248. cert=cert,
  249. proxies=proxies,
  250. allow_redirects=False,
  251. **adapter_kwargs,
  252. )
  253. extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)
  254. # extract redirect url, if any, for the next loop
  255. url = self.get_redirect_target(resp)
  256. yield resp
  257. def rebuild_auth(
  258. self, prepared_request: PreparedRequest, response: Response
  259. ) -> None:
  260. """When being redirected we may want to strip authentication from the
  261. request to avoid leaking credentials. This method intelligently removes
  262. and reapplies authentication where possible to avoid credential loss.
  263. """
  264. original_request = response.request
  265. assert _is_prepared(original_request)
  266. assert _is_prepared(prepared_request)
  267. headers = prepared_request.headers
  268. original_url = original_request.url
  269. url = prepared_request.url
  270. if "Authorization" in headers and self.should_strip_auth(original_url, url):
  271. # If we get redirected to a new host, we should strip out any
  272. # authentication headers.
  273. del headers["Authorization"]
  274. # .netrc might have more auth for us on our new host.
  275. new_auth = get_netrc_auth(url) if self.trust_env else None
  276. if new_auth is not None:
  277. prepared_request.prepare_auth(new_auth)
  278. def rebuild_proxies(
  279. self,
  280. prepared_request: PreparedRequest,
  281. proxies: dict[str, str] | None,
  282. ) -> dict[str, str]:
  283. """This method re-evaluates the proxy configuration by considering the
  284. environment variables. If we are redirected to a URL covered by
  285. NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
  286. proxy keys for this URL (in case they were stripped by a previous
  287. redirect).
  288. This method also replaces the Proxy-Authorization header where
  289. necessary.
  290. :rtype: dict
  291. """
  292. assert _is_prepared(prepared_request)
  293. headers = prepared_request.headers
  294. scheme = urlparse(prepared_request.url).scheme
  295. new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)
  296. if "Proxy-Authorization" in headers:
  297. del headers["Proxy-Authorization"]
  298. try:
  299. username, password = get_auth_from_url(new_proxies[scheme])
  300. except KeyError:
  301. username, password = None, None
  302. # urllib3 handles proxy authorization for us in the standard adapter.
  303. # Avoid appending this to TLS tunneled requests where it may be leaked.
  304. if not scheme.startswith("https") and username and password:
  305. headers["Proxy-Authorization"] = _basic_auth_str(username, password)
  306. return new_proxies
  307. def rebuild_method(
  308. self, prepared_request: PreparedRequest, response: Response
  309. ) -> None:
  310. """When being redirected we may want to change the method of the request
  311. based on certain specs or browser behavior.
  312. """
  313. method = prepared_request.method
  314. # https://tools.ietf.org/html/rfc7231#section-6.4.4
  315. if response.status_code == codes.see_other and method != "HEAD":
  316. method = "GET"
  317. # Do what the browsers do, despite standards...
  318. # First, turn 302s into GETs.
  319. if response.status_code == codes.found and method != "HEAD":
  320. method = "GET"
  321. # Second, if a POST is responded to with a 301, turn it into a GET.
  322. # This bizarre behaviour is explained in Issue 1704.
  323. if response.status_code == codes.moved and method == "POST":
  324. method = "GET"
  325. prepared_request.method = method
  326. class Session(SessionRedirectMixin):
  327. """A Requests session.
  328. Provides cookie persistence, connection-pooling, and configuration.
  329. Basic Usage::
  330. >>> import requests
  331. >>> s = requests.Session()
  332. >>> s.get('https://httpbin.org/get')
  333. <Response [200]>
  334. Or as a context manager::
  335. >>> with requests.Session() as s:
  336. ... s.get('https://httpbin.org/get')
  337. <Response [200]>
  338. """
  339. headers: CaseInsensitiveDict[str]
  340. auth: _t.AuthType
  341. proxies: dict[str, str]
  342. hooks: dict[str, list[_t.HookType]]
  343. params: MutableMapping[str, Any]
  344. stream: bool
  345. verify: _t.VerifyType
  346. cert: _t.CertType
  347. max_redirects: int
  348. trust_env: bool
  349. cookies: RequestsCookieJar
  350. adapters: MutableMapping[str, BaseAdapter]
  351. __attrs__: list[str] = [
  352. "headers",
  353. "cookies",
  354. "auth",
  355. "proxies",
  356. "hooks",
  357. "params",
  358. "verify",
  359. "cert",
  360. "adapters",
  361. "stream",
  362. "trust_env",
  363. "max_redirects",
  364. ]
  365. def __init__(self) -> None:
  366. #: A case-insensitive dictionary of headers to be sent on each
  367. #: :class:`Request <Request>` sent from this
  368. #: :class:`Session <Session>`.
  369. self.headers = default_headers()
  370. #: Default Authentication tuple or object to attach to
  371. #: :class:`Request <Request>`.
  372. self.auth = None
  373. #: Dictionary mapping protocol or protocol and host to the URL of the proxy
  374. #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to
  375. #: be used on each :class:`Request <Request>`.
  376. self.proxies = {}
  377. #: Event-handling hooks.
  378. self.hooks = default_hooks()
  379. #: Dictionary of querystring data to attach to each
  380. #: :class:`Request <Request>`. The dictionary values may be lists for
  381. #: representing multivalued query parameters.
  382. self.params = {}
  383. #: Stream response content default.
  384. self.stream = False
  385. #: SSL Verification default.
  386. #: Defaults to `True`, requiring requests to verify the TLS certificate at the
  387. #: remote end.
  388. #: If verify is set to `False`, requests will accept any TLS certificate
  389. #: presented by the server, and will ignore hostname mismatches and/or
  390. #: expired certificates, which will make your application vulnerable to
  391. #: man-in-the-middle (MitM) attacks.
  392. #: Only set this to `False` for testing.
  393. #: If verify is set to a string, it must be the path to a CA bundle file
  394. #: that will be used to verify the TLS certificate.
  395. self.verify = True
  396. #: SSL client certificate default, if String, path to ssl client
  397. #: cert file (.pem). If Tuple, ('cert', 'key') pair.
  398. self.cert = None
  399. #: Maximum number of redirects allowed. If the request exceeds this
  400. #: limit, a :class:`TooManyRedirects` exception is raised.
  401. #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is
  402. #: 30.
  403. self.max_redirects = DEFAULT_REDIRECT_LIMIT
  404. #: Trust environment settings for proxy configuration, default
  405. #: authentication and similar.
  406. self.trust_env = True
  407. #: A CookieJar containing all currently outstanding cookies set on this
  408. #: session. By default it is a
  409. #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but
  410. #: may be any other ``cookielib.CookieJar`` compatible object.
  411. self.cookies = cookiejar_from_dict({})
  412. # Default connection adapters.
  413. self.adapters = OrderedDict()
  414. self.mount("https://", HTTPAdapter())
  415. self.mount("http://", HTTPAdapter())
  416. def __enter__(self) -> Self:
  417. return self
  418. def __exit__(self, *args: Any) -> None:
  419. self.close()
  420. def prepare_request(self, request: Request) -> PreparedRequest:
  421. """Constructs a :class:`PreparedRequest <PreparedRequest>` for
  422. transmission and returns it. The :class:`PreparedRequest` has settings
  423. merged from the :class:`Request <Request>` instance and those of the
  424. :class:`Session`.
  425. :param request: :class:`Request` instance to prepare with this
  426. session's settings.
  427. :rtype: requests.PreparedRequest
  428. """
  429. url = cast("_t.UriType", request.url)
  430. method = cast(str, request.method)
  431. cookies = request.cookies or {}
  432. # Bootstrap CookieJar.
  433. if not isinstance(cookies, cookielib.CookieJar):
  434. cookies = cookiejar_from_dict(cookies)
  435. # Merge with session cookies
  436. merged_cookies = merge_cookies(
  437. merge_cookies(RequestsCookieJar(), self.cookies), cookies
  438. )
  439. # Set environment's basic authentication if not explicitly set.
  440. auth = request.auth
  441. if self.trust_env and not auth and not self.auth:
  442. auth = get_netrc_auth(url)
  443. p = PreparedRequest()
  444. p.prepare(
  445. method=method.upper(),
  446. url=url,
  447. files=request.files,
  448. data=request.data,
  449. json=request.json,
  450. headers=merge_setting(
  451. request.headers, self.headers, dict_class=CaseInsensitiveDict
  452. ),
  453. params=merge_setting(request.params, self.params),
  454. auth=merge_setting(auth, self.auth),
  455. cookies=merged_cookies,
  456. hooks=merge_hooks(request.hooks, self.hooks),
  457. )
  458. return p
  459. def request(
  460. self,
  461. method: str,
  462. url: _t.UriType,
  463. params: _t.ParamsType = None,
  464. data: _t.DataType = None,
  465. headers: _t.HeadersType = None,
  466. cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None,
  467. files: _t.FilesType = None,
  468. auth: _t.AuthType = None,
  469. timeout: _t.TimeoutType = None,
  470. allow_redirects: bool = True,
  471. proxies: dict[str, str] | None = None,
  472. hooks: _t.HooksInputType | None = None,
  473. stream: bool | None = None,
  474. verify: _t.VerifyType | None = None,
  475. cert: _t.CertType = None,
  476. json: _t.JsonType = None,
  477. ) -> Response:
  478. """Constructs a :class:`Request <Request>`, prepares it and sends it.
  479. Returns :class:`Response <Response>` object.
  480. :param method: method for the new :class:`Request` object.
  481. :param url: URL for the new :class:`Request` object.
  482. :param params: (optional) Dictionary or bytes to be sent in the query
  483. string for the :class:`Request`.
  484. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  485. object to send in the body of the :class:`Request`.
  486. :param json: (optional) json to send in the body of the
  487. :class:`Request`.
  488. :param headers: (optional) Dictionary of HTTP Headers to send with the
  489. :class:`Request`.
  490. :param cookies: (optional) Dict or CookieJar object to send with the
  491. :class:`Request`.
  492. :param files: (optional) Dictionary of ``'filename': file-like-objects``
  493. for multipart encoding upload.
  494. :param auth: (optional) Auth tuple or callable to enable
  495. Basic/Digest/Custom HTTP Auth.
  496. :param timeout: (optional) How many seconds to wait for the server to send
  497. data before giving up, as a float, or a :ref:`(connect timeout,
  498. read timeout) <timeouts>` tuple.
  499. :type timeout: float or tuple
  500. :param allow_redirects: (optional) Set to True by default.
  501. :type allow_redirects: bool
  502. :param proxies: (optional) Dictionary mapping protocol or protocol and
  503. hostname to the URL of the proxy.
  504. :param hooks: (optional) Dictionary mapping hook name to one event or
  505. list of events, event must be callable.
  506. :param stream: (optional) whether to immediately download the response
  507. content. Defaults to ``False``.
  508. :param verify: (optional) Either a boolean, in which case it controls whether we verify
  509. the server's TLS certificate, or a string, in which case it must be a path
  510. to a CA bundle to use. Defaults to ``True``. When set to
  511. ``False``, requests will accept any TLS certificate presented by
  512. the server, and will ignore hostname mismatches and/or expired
  513. certificates, which will make your application vulnerable to
  514. man-in-the-middle (MitM) attacks. Setting verify to ``False``
  515. may be useful during local development or testing.
  516. :param cert: (optional) if String, path to ssl client cert file (.pem).
  517. If Tuple, ('cert', 'key') pair.
  518. :rtype: requests.Response
  519. """
  520. if isinstance(url, bytes):
  521. url = url.decode("utf-8")
  522. # Create the Request.
  523. req = Request(
  524. method=method.upper(),
  525. url=url,
  526. headers=headers,
  527. files=files,
  528. data=data or {},
  529. json=json,
  530. params=params or {},
  531. auth=auth,
  532. cookies=cookies,
  533. hooks=hooks,
  534. )
  535. prep = self.prepare_request(req)
  536. assert _is_prepared(prep)
  537. proxies = proxies or {}
  538. settings = self.merge_environment_settings(
  539. prep.url, proxies, stream, verify, cert
  540. )
  541. # Send the request.
  542. send_kwargs = {
  543. "timeout": timeout,
  544. "allow_redirects": allow_redirects,
  545. }
  546. send_kwargs.update(settings)
  547. resp = self.send(prep, **send_kwargs)
  548. return resp
  549. def get(
  550. self,
  551. url: _t.UriType,
  552. params: _t.ParamsType = None,
  553. **kwargs: Unpack[_t.GetKwargs],
  554. ) -> Response:
  555. r"""Sends a GET request. Returns :class:`Response` object.
  556. :param url: URL for the new :class:`Request` object.
  557. :param params: (optional) Dictionary, list of tuples or bytes to send
  558. in the query string for the :class:`Request`.
  559. :param \*\*kwargs: Optional arguments that ``request`` takes.
  560. :rtype: requests.Response
  561. """
  562. kwargs.setdefault("allow_redirects", True)
  563. return self.request("GET", url, params=params, **kwargs)
  564. def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:
  565. r"""Sends a OPTIONS request. Returns :class:`Response` object.
  566. :param url: URL for the new :class:`Request` object.
  567. :param \*\*kwargs: Optional arguments that ``request`` takes.
  568. :rtype: requests.Response
  569. """
  570. kwargs.setdefault("allow_redirects", True)
  571. return self.request("OPTIONS", url, **kwargs)
  572. def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:
  573. r"""Sends a HEAD request. Returns :class:`Response` object.
  574. :param url: URL for the new :class:`Request` object.
  575. :param \*\*kwargs: Optional arguments that ``request`` takes.
  576. :rtype: requests.Response
  577. """
  578. kwargs.setdefault("allow_redirects", False)
  579. return self.request("HEAD", url, **kwargs)
  580. def post(
  581. self,
  582. url: _t.UriType,
  583. data: _t.DataType = None,
  584. json: _t.JsonType = None,
  585. **kwargs: Unpack[_t.PostKwargs],
  586. ) -> Response:
  587. r"""Sends a POST request. Returns :class:`Response` object.
  588. :param url: URL for the new :class:`Request` object.
  589. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  590. object to send in the body of the :class:`Request`.
  591. :param json: (optional) json to send in the body of the :class:`Request`.
  592. :param \*\*kwargs: Optional arguments that ``request`` takes.
  593. :rtype: requests.Response
  594. """
  595. return self.request("POST", url, data=data, json=json, **kwargs)
  596. def put(
  597. self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]
  598. ) -> Response:
  599. r"""Sends a PUT request. Returns :class:`Response` object.
  600. :param url: URL for the new :class:`Request` object.
  601. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  602. object to send in the body of the :class:`Request`.
  603. :param \*\*kwargs: Optional arguments that ``request`` takes.
  604. :rtype: requests.Response
  605. """
  606. return self.request("PUT", url, data=data, **kwargs)
  607. def patch(
  608. self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]
  609. ) -> Response:
  610. r"""Sends a PATCH request. Returns :class:`Response` object.
  611. :param url: URL for the new :class:`Request` object.
  612. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  613. object to send in the body of the :class:`Request`.
  614. :param \*\*kwargs: Optional arguments that ``request`` takes.
  615. :rtype: requests.Response
  616. """
  617. return self.request("PATCH", url, data=data, **kwargs)
  618. def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:
  619. r"""Sends a DELETE request. Returns :class:`Response` object.
  620. :param url: URL for the new :class:`Request` object.
  621. :param \*\*kwargs: Optional arguments that ``request`` takes.
  622. :rtype: requests.Response
  623. """
  624. return self.request("DELETE", url, **kwargs)
  625. def send(self, request: PreparedRequest, **kwargs: Any) -> Response:
  626. """Send a given PreparedRequest.
  627. :rtype: requests.Response
  628. """
  629. # Set defaults that the hooks can utilize to ensure they always have
  630. # the correct parameters to reproduce the previous request.
  631. kwargs.setdefault("stream", self.stream)
  632. kwargs.setdefault("verify", self.verify)
  633. kwargs.setdefault("cert", self.cert)
  634. if "proxies" not in kwargs:
  635. kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env)
  636. # It's possible that users might accidentally send a Request object.
  637. # Guard against that specific failure case.
  638. if isinstance(request, Request):
  639. raise ValueError("You can only send PreparedRequests.")
  640. assert _is_prepared(request)
  641. # Set up variables needed for resolve_redirects and dispatching of hooks
  642. allow_redirects = kwargs.pop("allow_redirects", True)
  643. stream = kwargs.get("stream")
  644. hooks = request.hooks
  645. # Get the appropriate adapter to use
  646. adapter = self.get_adapter(url=request.url)
  647. # Start time (approximately) of the request
  648. start = preferred_clock()
  649. # Send the request
  650. r = adapter.send(request, **kwargs)
  651. # Total elapsed time of the request (approximately)
  652. elapsed = preferred_clock() - start
  653. r.elapsed = timedelta(seconds=elapsed)
  654. # Response manipulation hooks
  655. r = dispatch_hook("response", hooks, r, **kwargs)
  656. # Persist cookies
  657. if r.history:
  658. # If the hooks create history then we want those cookies too
  659. for resp in r.history:
  660. extract_cookies_to_jar(self.cookies, resp.request, resp.raw)
  661. extract_cookies_to_jar(self.cookies, request, r.raw)
  662. # Resolve redirects if allowed.
  663. if allow_redirects:
  664. # Redirect resolving generator.
  665. gen = self.resolve_redirects(r, request, **kwargs)
  666. history = [resp for resp in gen]
  667. else:
  668. history = []
  669. # Shuffle things around if there's history.
  670. if history:
  671. # Insert the first (original) request at the start
  672. history.insert(0, r)
  673. # Get the last request made
  674. r = history.pop()
  675. r.history = history
  676. # If redirects aren't being followed, store the response on the Request for Response.next().
  677. if not allow_redirects:
  678. try:
  679. r._next = next( # type: ignore[assignment] # yield_requests=True returns PreparedRequest
  680. self.resolve_redirects(r, request, yield_requests=True, **kwargs)
  681. )
  682. except StopIteration:
  683. pass
  684. if not stream:
  685. r.content
  686. return r
  687. def merge_environment_settings(
  688. self,
  689. url: str,
  690. proxies: dict[str, str] | None,
  691. stream: bool | None,
  692. verify: _t.VerifyType | None,
  693. cert: _t.CertType,
  694. ) -> dict[str, Any]:
  695. """
  696. Check the environment and merge it with some settings.
  697. :rtype: dict
  698. """
  699. # Gather clues from the surrounding environment.
  700. if self.trust_env:
  701. # Set environment's proxies.
  702. no_proxy = proxies.get("no_proxy") if proxies is not None else None
  703. env_proxies = get_environ_proxies(url, no_proxy=no_proxy)
  704. if proxies is not None:
  705. for k, v in env_proxies.items():
  706. proxies.setdefault(k, v)
  707. # Look for requests environment configuration
  708. # and be compatible with cURL.
  709. if verify is True or verify is None:
  710. verify = (
  711. os.environ.get("REQUESTS_CA_BUNDLE")
  712. or os.environ.get("CURL_CA_BUNDLE")
  713. or verify
  714. )
  715. # Merge all the kwargs.
  716. proxies = merge_setting(proxies, self.proxies)
  717. stream = merge_setting(stream, self.stream)
  718. verify = merge_setting(verify, self.verify)
  719. cert = merge_setting(cert, self.cert)
  720. return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}
  721. def get_adapter(self, url: str) -> BaseAdapter:
  722. """
  723. Returns the appropriate connection adapter for the given URL.
  724. :rtype: requests.adapters.BaseAdapter
  725. """
  726. for prefix, adapter in self.adapters.items():
  727. if url.lower().startswith(prefix.lower()):
  728. return adapter
  729. # Nothing matches :-/
  730. raise InvalidSchema(f"No connection adapters were found for {url!r}")
  731. def close(self) -> None:
  732. """Closes all adapters and as such the session"""
  733. for v in self.adapters.values():
  734. v.close()
  735. def mount(self, prefix: str, adapter: BaseAdapter) -> None:
  736. """Registers a connection adapter to a prefix.
  737. Adapters are sorted in descending order by prefix length.
  738. """
  739. self.adapters[prefix] = adapter
  740. keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
  741. for key in keys_to_move:
  742. self.adapters[key] = self.adapters.pop(key)
  743. def __getstate__(self) -> dict[str, Any]:
  744. state = {attr: getattr(self, attr, None) for attr in self.__attrs__}
  745. return state
  746. def __setstate__(self, state: dict[str, Any]) -> None:
  747. for attr, value in state.items():
  748. setattr(self, attr, value)
  749. def session() -> Session:
  750. """
  751. Returns a :class:`Session` for context-management.
  752. .. deprecated:: 1.0.0
  753. This method has been deprecated since version 1.0.0 and is only kept for
  754. backwards compatibility. New code should use :class:`~requests.sessions.Session`
  755. to create a session. This may be removed at a future date.
  756. :rtype: Session
  757. """
  758. return Session()