sessions.py 29 KB

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