sessions.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. # -*- coding: utf-8 -*-
  2. """
  3. requests.session
  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
  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. proxies = proxies if proxies is not None else {}
  229. headers = prepared_request.headers
  230. url = prepared_request.url
  231. scheme = urlparse(url).scheme
  232. new_proxies = proxies.copy()
  233. no_proxy = proxies.get('no_proxy')
  234. bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy)
  235. if self.trust_env and not bypass_proxy:
  236. environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)
  237. proxy = environ_proxies.get(scheme, environ_proxies.get('all'))
  238. if proxy:
  239. new_proxies.setdefault(scheme, proxy)
  240. if 'Proxy-Authorization' in headers:
  241. del headers['Proxy-Authorization']
  242. try:
  243. username, password = get_auth_from_url(new_proxies[scheme])
  244. except KeyError:
  245. username, password = None, None
  246. if username and password:
  247. headers['Proxy-Authorization'] = _basic_auth_str(username, password)
  248. return new_proxies
  249. def rebuild_method(self, prepared_request, response):
  250. """When being redirected we may want to change the method of the request
  251. based on certain specs or browser behavior.
  252. """
  253. method = prepared_request.method
  254. # https://tools.ietf.org/html/rfc7231#section-6.4.4
  255. if response.status_code == codes.see_other and method != 'HEAD':
  256. method = 'GET'
  257. # Do what the browsers do, despite standards...
  258. # First, turn 302s into GETs.
  259. if response.status_code == codes.found and method != 'HEAD':
  260. method = 'GET'
  261. # Second, if a POST is responded to with a 301, turn it into a GET.
  262. # This bizarre behaviour is explained in Issue 1704.
  263. if response.status_code == codes.moved and method == 'POST':
  264. method = 'GET'
  265. prepared_request.method = method
  266. class Session(SessionRedirectMixin):
  267. """A Requests session.
  268. Provides cookie persistence, connection-pooling, and configuration.
  269. Basic Usage::
  270. >>> import requests
  271. >>> s = requests.Session()
  272. >>> s.get('https://httpbin.org/get')
  273. <Response [200]>
  274. Or as a context manager::
  275. >>> with requests.Session() as s:
  276. ... s.get('https://httpbin.org/get')
  277. <Response [200]>
  278. """
  279. __attrs__ = [
  280. 'headers', 'cookies', 'auth', 'proxies', 'hooks', 'params', 'verify',
  281. 'cert', 'adapters', 'stream', 'trust_env',
  282. 'max_redirects',
  283. ]
  284. def __init__(self):
  285. #: A case-insensitive dictionary of headers to be sent on each
  286. #: :class:`Request <Request>` sent from this
  287. #: :class:`Session <Session>`.
  288. self.headers = default_headers()
  289. #: Default Authentication tuple or object to attach to
  290. #: :class:`Request <Request>`.
  291. self.auth = None
  292. #: Dictionary mapping protocol or protocol and host to the URL of the proxy
  293. #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to
  294. #: be used on each :class:`Request <Request>`.
  295. self.proxies = {}
  296. #: Event-handling hooks.
  297. self.hooks = default_hooks()
  298. #: Dictionary of querystring data to attach to each
  299. #: :class:`Request <Request>`. The dictionary values may be lists for
  300. #: representing multivalued query parameters.
  301. self.params = {}
  302. #: Stream response content default.
  303. self.stream = False
  304. #: SSL Verification default.
  305. self.verify = True
  306. #: SSL client certificate default, if String, path to ssl client
  307. #: cert file (.pem). If Tuple, ('cert', 'key') pair.
  308. self.cert = None
  309. #: Maximum number of redirects allowed. If the request exceeds this
  310. #: limit, a :class:`TooManyRedirects` exception is raised.
  311. #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is
  312. #: 30.
  313. self.max_redirects = DEFAULT_REDIRECT_LIMIT
  314. #: Trust environment settings for proxy configuration, default
  315. #: authentication and similar.
  316. self.trust_env = True
  317. #: A CookieJar containing all currently outstanding cookies set on this
  318. #: session. By default it is a
  319. #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but
  320. #: may be any other ``cookielib.CookieJar`` compatible object.
  321. self.cookies = cookiejar_from_dict({})
  322. # Default connection adapters.
  323. self.adapters = OrderedDict()
  324. self.mount('https://', HTTPAdapter())
  325. self.mount('http://', HTTPAdapter())
  326. def __enter__(self):
  327. return self
  328. def __exit__(self, *args):
  329. self.close()
  330. def prepare_request(self, request):
  331. """Constructs a :class:`PreparedRequest <PreparedRequest>` for
  332. transmission and returns it. The :class:`PreparedRequest` has settings
  333. merged from the :class:`Request <Request>` instance and those of the
  334. :class:`Session`.
  335. :param request: :class:`Request` instance to prepare with this
  336. session's settings.
  337. :rtype: requests.PreparedRequest
  338. """
  339. cookies = request.cookies or {}
  340. # Bootstrap CookieJar.
  341. if not isinstance(cookies, cookielib.CookieJar):
  342. cookies = cookiejar_from_dict(cookies)
  343. # Merge with session cookies
  344. merged_cookies = merge_cookies(
  345. merge_cookies(RequestsCookieJar(), self.cookies), cookies)
  346. # Set environment's basic authentication if not explicitly set.
  347. auth = request.auth
  348. if self.trust_env and not auth and not self.auth:
  349. auth = get_netrc_auth(request.url)
  350. p = PreparedRequest()
  351. p.prepare(
  352. method=request.method.upper(),
  353. url=request.url,
  354. files=request.files,
  355. data=request.data,
  356. json=request.json,
  357. headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict),
  358. params=merge_setting(request.params, self.params),
  359. auth=merge_setting(auth, self.auth),
  360. cookies=merged_cookies,
  361. hooks=merge_hooks(request.hooks, self.hooks),
  362. )
  363. return p
  364. def request(self, method, url,
  365. params=None, data=None, headers=None, cookies=None, files=None,
  366. auth=None, timeout=None, allow_redirects=True, proxies=None,
  367. hooks=None, stream=None, verify=None, cert=None, json=None):
  368. """Constructs a :class:`Request <Request>`, prepares it and sends it.
  369. Returns :class:`Response <Response>` object.
  370. :param method: method for the new :class:`Request` object.
  371. :param url: URL for the new :class:`Request` object.
  372. :param params: (optional) Dictionary or bytes to be sent in the query
  373. string for the :class:`Request`.
  374. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  375. object to send in the body of the :class:`Request`.
  376. :param json: (optional) json to send in the body of the
  377. :class:`Request`.
  378. :param headers: (optional) Dictionary of HTTP Headers to send with the
  379. :class:`Request`.
  380. :param cookies: (optional) Dict or CookieJar object to send with the
  381. :class:`Request`.
  382. :param files: (optional) Dictionary of ``'filename': file-like-objects``
  383. for multipart encoding upload.
  384. :param auth: (optional) Auth tuple or callable to enable
  385. Basic/Digest/Custom HTTP Auth.
  386. :param timeout: (optional) How long to wait for the server to send
  387. data before giving up, as a float, or a :ref:`(connect timeout,
  388. read timeout) <timeouts>` tuple.
  389. :type timeout: float or tuple
  390. :param allow_redirects: (optional) Set to True by default.
  391. :type allow_redirects: bool
  392. :param proxies: (optional) Dictionary mapping protocol or protocol and
  393. hostname to the URL of the proxy.
  394. :param stream: (optional) whether to immediately download the response
  395. content. Defaults to ``False``.
  396. :param verify: (optional) Either a boolean, in which case it controls whether we verify
  397. the server's TLS certificate, or a string, in which case it must be a path
  398. to a CA bundle to use. Defaults to ``True``.
  399. :param cert: (optional) if String, path to ssl client cert file (.pem).
  400. If Tuple, ('cert', 'key') pair.
  401. :rtype: requests.Response
  402. """
  403. # Create the Request.
  404. req = Request(
  405. method=method.upper(),
  406. url=url,
  407. headers=headers,
  408. files=files,
  409. data=data or {},
  410. json=json,
  411. params=params or {},
  412. auth=auth,
  413. cookies=cookies,
  414. hooks=hooks,
  415. )
  416. prep = self.prepare_request(req)
  417. proxies = proxies or {}
  418. settings = self.merge_environment_settings(
  419. prep.url, proxies, stream, verify, cert
  420. )
  421. # Send the request.
  422. send_kwargs = {
  423. 'timeout': timeout,
  424. 'allow_redirects': allow_redirects,
  425. }
  426. send_kwargs.update(settings)
  427. resp = self.send(prep, **send_kwargs)
  428. return resp
  429. def get(self, url, **kwargs):
  430. r"""Sends a GET request. Returns :class:`Response` object.
  431. :param url: URL for the new :class:`Request` object.
  432. :param \*\*kwargs: Optional arguments that ``request`` takes.
  433. :rtype: requests.Response
  434. """
  435. kwargs.setdefault('allow_redirects', True)
  436. return self.request('GET', url, **kwargs)
  437. def options(self, url, **kwargs):
  438. r"""Sends a OPTIONS request. Returns :class:`Response` object.
  439. :param url: URL for the new :class:`Request` object.
  440. :param \*\*kwargs: Optional arguments that ``request`` takes.
  441. :rtype: requests.Response
  442. """
  443. kwargs.setdefault('allow_redirects', True)
  444. return self.request('OPTIONS', url, **kwargs)
  445. def head(self, url, **kwargs):
  446. r"""Sends a HEAD request. Returns :class:`Response` object.
  447. :param url: URL for the new :class:`Request` object.
  448. :param \*\*kwargs: Optional arguments that ``request`` takes.
  449. :rtype: requests.Response
  450. """
  451. kwargs.setdefault('allow_redirects', False)
  452. return self.request('HEAD', url, **kwargs)
  453. def post(self, url, data=None, json=None, **kwargs):
  454. r"""Sends a POST request. Returns :class:`Response` object.
  455. :param url: URL for the new :class:`Request` object.
  456. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  457. object to send in the body of the :class:`Request`.
  458. :param json: (optional) json to send in the body of the :class:`Request`.
  459. :param \*\*kwargs: Optional arguments that ``request`` takes.
  460. :rtype: requests.Response
  461. """
  462. return self.request('POST', url, data=data, json=json, **kwargs)
  463. def put(self, url, data=None, **kwargs):
  464. r"""Sends a PUT request. Returns :class:`Response` object.
  465. :param url: URL for the new :class:`Request` object.
  466. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  467. object to send in the body of the :class:`Request`.
  468. :param \*\*kwargs: Optional arguments that ``request`` takes.
  469. :rtype: requests.Response
  470. """
  471. return self.request('PUT', url, data=data, **kwargs)
  472. def patch(self, url, data=None, **kwargs):
  473. r"""Sends a PATCH request. Returns :class:`Response` object.
  474. :param url: URL for the new :class:`Request` object.
  475. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  476. object to send in the body of the :class:`Request`.
  477. :param \*\*kwargs: Optional arguments that ``request`` takes.
  478. :rtype: requests.Response
  479. """
  480. return self.request('PATCH', url, data=data, **kwargs)
  481. def delete(self, url, **kwargs):
  482. r"""Sends a DELETE request. Returns :class:`Response` object.
  483. :param url: URL for the new :class:`Request` object.
  484. :param \*\*kwargs: Optional arguments that ``request`` takes.
  485. :rtype: requests.Response
  486. """
  487. return self.request('DELETE', url, **kwargs)
  488. def send(self, request, **kwargs):
  489. """Send a given PreparedRequest.
  490. :rtype: requests.Response
  491. """
  492. # Set defaults that the hooks can utilize to ensure they always have
  493. # the correct parameters to reproduce the previous request.
  494. kwargs.setdefault('stream', self.stream)
  495. kwargs.setdefault('verify', self.verify)
  496. kwargs.setdefault('cert', self.cert)
  497. kwargs.setdefault('proxies', self.proxies)
  498. # It's possible that users might accidentally send a Request object.
  499. # Guard against that specific failure case.
  500. if isinstance(request, Request):
  501. raise ValueError('You can only send PreparedRequests.')
  502. # Set up variables needed for resolve_redirects and dispatching of hooks
  503. allow_redirects = kwargs.pop('allow_redirects', True)
  504. stream = kwargs.get('stream')
  505. hooks = request.hooks
  506. # Get the appropriate adapter to use
  507. adapter = self.get_adapter(url=request.url)
  508. # Start time (approximately) of the request
  509. start = preferred_clock()
  510. # Send the request
  511. r = adapter.send(request, **kwargs)
  512. # Total elapsed time of the request (approximately)
  513. elapsed = preferred_clock() - start
  514. r.elapsed = timedelta(seconds=elapsed)
  515. # Response manipulation hooks
  516. r = dispatch_hook('response', hooks, r, **kwargs)
  517. # Persist cookies
  518. if r.history:
  519. # If the hooks create history then we want those cookies too
  520. for resp in r.history:
  521. extract_cookies_to_jar(self.cookies, resp.request, resp.raw)
  522. extract_cookies_to_jar(self.cookies, request, r.raw)
  523. # Redirect resolving generator.
  524. gen = self.resolve_redirects(r, request, **kwargs)
  525. # Resolve redirects if allowed.
  526. history = [resp for resp in gen] if allow_redirects else []
  527. # Shuffle things around if there's history.
  528. if history:
  529. # Insert the first (original) request at the start
  530. history.insert(0, r)
  531. # Get the last request made
  532. r = history.pop()
  533. r.history = history
  534. # If redirects aren't being followed, store the response on the Request for Response.next().
  535. if not allow_redirects:
  536. try:
  537. r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs))
  538. except StopIteration:
  539. pass
  540. if not stream:
  541. r.content
  542. return r
  543. def merge_environment_settings(self, url, proxies, stream, verify, cert):
  544. """
  545. Check the environment and merge it with some settings.
  546. :rtype: dict
  547. """
  548. # Gather clues from the surrounding environment.
  549. if self.trust_env:
  550. # Set environment's proxies.
  551. no_proxy = proxies.get('no_proxy') if proxies is not None else None
  552. env_proxies = get_environ_proxies(url, no_proxy=no_proxy)
  553. for (k, v) in env_proxies.items():
  554. proxies.setdefault(k, v)
  555. # Look for requests environment configuration and be compatible
  556. # with cURL.
  557. if verify is True or verify is None:
  558. verify = (os.environ.get('REQUESTS_CA_BUNDLE') or
  559. os.environ.get('CURL_CA_BUNDLE'))
  560. # Merge all the kwargs.
  561. proxies = merge_setting(proxies, self.proxies)
  562. stream = merge_setting(stream, self.stream)
  563. verify = merge_setting(verify, self.verify)
  564. cert = merge_setting(cert, self.cert)
  565. return {'verify': verify, 'proxies': proxies, 'stream': stream,
  566. 'cert': cert}
  567. def get_adapter(self, url):
  568. """
  569. Returns the appropriate connection adapter for the given URL.
  570. :rtype: requests.adapters.BaseAdapter
  571. """
  572. for (prefix, adapter) in self.adapters.items():
  573. if url.lower().startswith(prefix.lower()):
  574. return adapter
  575. # Nothing matches :-/
  576. raise InvalidSchema("No connection adapters were found for {!r}".format(url))
  577. def close(self):
  578. """Closes all adapters and as such the session"""
  579. for v in self.adapters.values():
  580. v.close()
  581. def mount(self, prefix, adapter):
  582. """Registers a connection adapter to a prefix.
  583. Adapters are sorted in descending order by prefix length.
  584. """
  585. self.adapters[prefix] = adapter
  586. keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
  587. for key in keys_to_move:
  588. self.adapters[key] = self.adapters.pop(key)
  589. def __getstate__(self):
  590. state = {attr: getattr(self, attr, None) for attr in self.__attrs__}
  591. return state
  592. def __setstate__(self, state):
  593. for attr, value in state.items():
  594. setattr(self, attr, value)
  595. def session():
  596. """
  597. Returns a :class:`Session` for context-management.
  598. .. deprecated:: 1.0.0
  599. This method has been deprecated since version 1.0.0 and is only kept for
  600. backwards compatibility. New code should use :class:`~requests.sessions.Session`
  601. to create a session. This may be removed at a future date.
  602. :rtype: Session
  603. """
  604. return Session()