You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sessions.py 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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 platform
  10. import time
  11. from collections import Mapping
  12. from datetime import timedelta
  13. from .auth import _basic_auth_str
  14. from .compat import cookielib, is_py3, OrderedDict, urljoin, urlparse
  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
  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 platform.system() == 'Windows':
  34. try: # Python 3.3+
  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 resolve_redirects(self, resp, req, stream=False, timeout=None,
  95. verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs):
  96. """Receives a Response. Returns a generator of Responses or Requests."""
  97. hist = [] # keep track of history
  98. url = self.get_redirect_target(resp)
  99. while url:
  100. prepared_request = req.copy()
  101. # Update history and keep track of redirects.
  102. # resp.history must ignore the original request in this loop
  103. hist.append(resp)
  104. resp.history = hist[1:]
  105. try:
  106. resp.content # Consume socket so it can be released
  107. except (ChunkedEncodingError, ContentDecodingError, RuntimeError):
  108. resp.raw.read(decode_content=False)
  109. if len(resp.history) >= self.max_redirects:
  110. raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects, response=resp)
  111. # Release the connection back into the pool.
  112. resp.close()
  113. # Handle redirection without scheme (see: RFC 1808 Section 4)
  114. if url.startswith('//'):
  115. parsed_rurl = urlparse(resp.url)
  116. url = '%s:%s' % (to_native_string(parsed_rurl.scheme), url)
  117. # The scheme should be lower case...
  118. parsed = urlparse(url)
  119. url = parsed.geturl()
  120. # Facilitate relative 'location' headers, as allowed by RFC 7231.
  121. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
  122. # Compliant with RFC3986, we percent encode the url.
  123. if not parsed.netloc:
  124. url = urljoin(resp.url, requote_uri(url))
  125. else:
  126. url = requote_uri(url)
  127. prepared_request.url = to_native_string(url)
  128. self.rebuild_method(prepared_request, resp)
  129. # https://github.com/requests/requests/issues/1084
  130. if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect):
  131. # https://github.com/requests/requests/issues/3490
  132. purged_headers = ('Content-Length', 'Content-Type', 'Transfer-Encoding')
  133. for header in purged_headers:
  134. prepared_request.headers.pop(header, None)
  135. prepared_request.body = None
  136. headers = prepared_request.headers
  137. try:
  138. del headers['Cookie']
  139. except KeyError:
  140. pass
  141. # Extract any cookies sent on the response to the cookiejar
  142. # in the new request. Because we've mutated our copied prepared
  143. # request, use the old one that we haven't yet touched.
  144. extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)
  145. merge_cookies(prepared_request._cookies, self.cookies)
  146. prepared_request.prepare_cookies(prepared_request._cookies)
  147. # Rebuild auth and proxy information.
  148. proxies = self.rebuild_proxies(prepared_request, proxies)
  149. self.rebuild_auth(prepared_request, resp)
  150. # A failed tell() sets `_body_position` to `object()`. This non-None
  151. # value ensures `rewindable` will be True, allowing us to raise an
  152. # UnrewindableBodyError, instead of hanging the connection.
  153. rewindable = (
  154. prepared_request._body_position is not None and
  155. ('Content-Length' in headers or 'Transfer-Encoding' in headers)
  156. )
  157. # Attempt to rewind consumed file-like object.
  158. if rewindable:
  159. rewind_body(prepared_request)
  160. # Override the original request.
  161. req = prepared_request
  162. if yield_requests:
  163. yield req
  164. else:
  165. resp = self.send(
  166. req,
  167. stream=stream,
  168. timeout=timeout,
  169. verify=verify,
  170. cert=cert,
  171. proxies=proxies,
  172. allow_redirects=False,
  173. **adapter_kwargs
  174. )
  175. extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)
  176. # extract redirect url, if any, for the next loop
  177. url = self.get_redirect_target(resp)
  178. yield resp
  179. def rebuild_auth(self, prepared_request, response):
  180. """When being redirected we may want to strip authentication from the
  181. request to avoid leaking credentials. This method intelligently removes
  182. and reapplies authentication where possible to avoid credential loss.
  183. """
  184. headers = prepared_request.headers
  185. url = prepared_request.url
  186. if 'Authorization' in headers:
  187. # If we get redirected to a new host, we should strip out any
  188. # authentication headers.
  189. original_parsed = urlparse(response.request.url)
  190. redirect_parsed = urlparse(url)
  191. if (original_parsed.hostname != redirect_parsed.hostname):
  192. del headers['Authorization']
  193. # .netrc might have more auth for us on our new host.
  194. new_auth = get_netrc_auth(url) if self.trust_env else None
  195. if new_auth is not None:
  196. prepared_request.prepare_auth(new_auth)
  197. return
  198. def rebuild_proxies(self, prepared_request, proxies):
  199. """This method re-evaluates the proxy configuration by considering the
  200. environment variables. If we are redirected to a URL covered by
  201. NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
  202. proxy keys for this URL (in case they were stripped by a previous
  203. redirect).
  204. This method also replaces the Proxy-Authorization header where
  205. necessary.
  206. :rtype: dict
  207. """
  208. proxies = proxies if proxies is not None else {}
  209. headers = prepared_request.headers
  210. url = prepared_request.url
  211. scheme = urlparse(url).scheme
  212. new_proxies = proxies.copy()
  213. no_proxy = proxies.get('no_proxy')
  214. bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy)
  215. if self.trust_env and not bypass_proxy:
  216. environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)
  217. proxy = environ_proxies.get(scheme, environ_proxies.get('all'))
  218. if proxy:
  219. new_proxies.setdefault(scheme, proxy)
  220. if 'Proxy-Authorization' in headers:
  221. del headers['Proxy-Authorization']
  222. try:
  223. username, password = get_auth_from_url(new_proxies[scheme])
  224. except KeyError:
  225. username, password = None, None
  226. if username and password:
  227. headers['Proxy-Authorization'] = _basic_auth_str(username, password)
  228. return new_proxies
  229. def rebuild_method(self, prepared_request, response):
  230. """When being redirected we may want to change the method of the request
  231. based on certain specs or browser behavior.
  232. """
  233. method = prepared_request.method
  234. # http://tools.ietf.org/html/rfc7231#section-6.4.4
  235. if response.status_code == codes.see_other and method != 'HEAD':
  236. method = 'GET'
  237. # Do what the browsers do, despite standards...
  238. # First, turn 302s into GETs.
  239. if response.status_code == codes.found and method != 'HEAD':
  240. method = 'GET'
  241. # Second, if a POST is responded to with a 301, turn it into a GET.
  242. # This bizarre behaviour is explained in Issue 1704.
  243. if response.status_code == codes.moved and method == 'POST':
  244. method = 'GET'
  245. prepared_request.method = method
  246. class Session(SessionRedirectMixin):
  247. """A Requests session.
  248. Provides cookie persistence, connection-pooling, and configuration.
  249. Basic Usage::
  250. >>> import requests
  251. >>> s = requests.Session()
  252. >>> s.get('http://httpbin.org/get')
  253. <Response [200]>
  254. Or as a context manager::
  255. >>> with requests.Session() as s:
  256. >>> s.get('http://httpbin.org/get')
  257. <Response [200]>
  258. """
  259. __attrs__ = [
  260. 'headers', 'cookies', 'auth', 'proxies', 'hooks', 'params', 'verify',
  261. 'cert', 'prefetch', 'adapters', 'stream', 'trust_env',
  262. 'max_redirects',
  263. ]
  264. def __init__(self):
  265. #: A case-insensitive dictionary of headers to be sent on each
  266. #: :class:`Request <Request>` sent from this
  267. #: :class:`Session <Session>`.
  268. self.headers = default_headers()
  269. #: Default Authentication tuple or object to attach to
  270. #: :class:`Request <Request>`.
  271. self.auth = None
  272. #: Dictionary mapping protocol or protocol and host to the URL of the proxy
  273. #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to
  274. #: be used on each :class:`Request <Request>`.
  275. self.proxies = {}
  276. #: Event-handling hooks.
  277. self.hooks = default_hooks()
  278. #: Dictionary of querystring data to attach to each
  279. #: :class:`Request <Request>`. The dictionary values may be lists for
  280. #: representing multivalued query parameters.
  281. self.params = {}
  282. #: Stream response content default.
  283. self.stream = False
  284. #: SSL Verification default.
  285. self.verify = True
  286. #: SSL client certificate default, if String, path to ssl client
  287. #: cert file (.pem). If Tuple, ('cert', 'key') pair.
  288. self.cert = None
  289. #: Maximum number of redirects allowed. If the request exceeds this
  290. #: limit, a :class:`TooManyRedirects` exception is raised.
  291. #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is
  292. #: 30.
  293. self.max_redirects = DEFAULT_REDIRECT_LIMIT
  294. #: Trust environment settings for proxy configuration, default
  295. #: authentication and similar.
  296. self.trust_env = True
  297. #: A CookieJar containing all currently outstanding cookies set on this
  298. #: session. By default it is a
  299. #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but
  300. #: may be any other ``cookielib.CookieJar`` compatible object.
  301. self.cookies = cookiejar_from_dict({})
  302. # Default connection adapters.
  303. self.adapters = OrderedDict()
  304. self.mount('https://', HTTPAdapter())
  305. self.mount('http://', HTTPAdapter())
  306. def __enter__(self):
  307. return self
  308. def __exit__(self, *args):
  309. self.close()
  310. def prepare_request(self, request):
  311. """Constructs a :class:`PreparedRequest <PreparedRequest>` for
  312. transmission and returns it. The :class:`PreparedRequest` has settings
  313. merged from the :class:`Request <Request>` instance and those of the
  314. :class:`Session`.
  315. :param request: :class:`Request` instance to prepare with this
  316. session's settings.
  317. :rtype: requests.PreparedRequest
  318. """
  319. cookies = request.cookies or {}
  320. # Bootstrap CookieJar.
  321. if not isinstance(cookies, cookielib.CookieJar):
  322. cookies = cookiejar_from_dict(cookies)
  323. # Merge with session cookies
  324. merged_cookies = merge_cookies(
  325. merge_cookies(RequestsCookieJar(), self.cookies), cookies)
  326. # Set environment's basic authentication if not explicitly set.
  327. auth = request.auth
  328. if self.trust_env and not auth and not self.auth:
  329. auth = get_netrc_auth(request.url)
  330. p = PreparedRequest()
  331. p.prepare(
  332. method=request.method.upper(),
  333. url=request.url,
  334. files=request.files,
  335. data=request.data,
  336. json=request.json,
  337. headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict),
  338. params=merge_setting(request.params, self.params),
  339. auth=merge_setting(auth, self.auth),
  340. cookies=merged_cookies,
  341. hooks=merge_hooks(request.hooks, self.hooks),
  342. )
  343. return p
  344. def request(self, method, url,
  345. params=None, data=None, headers=None, cookies=None, files=None,
  346. auth=None, timeout=None, allow_redirects=True, proxies=None,
  347. hooks=None, stream=None, verify=None, cert=None, json=None):
  348. """Constructs a :class:`Request <Request>`, prepares it and sends it.
  349. Returns :class:`Response <Response>` object.
  350. :param method: method for the new :class:`Request` object.
  351. :param url: URL for the new :class:`Request` object.
  352. :param params: (optional) Dictionary or bytes to be sent in the query
  353. string for the :class:`Request`.
  354. :param data: (optional) Dictionary, bytes, or file-like object to send
  355. in the body of the :class:`Request`.
  356. :param json: (optional) json to send in the body of the
  357. :class:`Request`.
  358. :param headers: (optional) Dictionary of HTTP Headers to send with the
  359. :class:`Request`.
  360. :param cookies: (optional) Dict or CookieJar object to send with the
  361. :class:`Request`.
  362. :param files: (optional) Dictionary of ``'filename': file-like-objects``
  363. for multipart encoding upload.
  364. :param auth: (optional) Auth tuple or callable to enable
  365. Basic/Digest/Custom HTTP Auth.
  366. :param timeout: (optional) How long to wait for the server to send
  367. data before giving up, as a float, or a :ref:`(connect timeout,
  368. read timeout) <timeouts>` tuple.
  369. :type timeout: float or tuple
  370. :param allow_redirects: (optional) Set to True by default.
  371. :type allow_redirects: bool
  372. :param proxies: (optional) Dictionary mapping protocol or protocol and
  373. hostname to the URL of the proxy.
  374. :param stream: (optional) whether to immediately download the response
  375. content. Defaults to ``False``.
  376. :param verify: (optional) Either a boolean, in which case it controls whether we verify
  377. the server's TLS certificate, or a string, in which case it must be a path
  378. to a CA bundle to use. Defaults to ``True``.
  379. :param cert: (optional) if String, path to ssl client cert file (.pem).
  380. If Tuple, ('cert', 'key') pair.
  381. :rtype: requests.Response
  382. """
  383. # Create the Request.
  384. req = Request(
  385. method=method.upper(),
  386. url=url,
  387. headers=headers,
  388. files=files,
  389. data=data or {},
  390. json=json,
  391. params=params or {},
  392. auth=auth,
  393. cookies=cookies,
  394. hooks=hooks,
  395. )
  396. prep = self.prepare_request(req)
  397. proxies = proxies or {}
  398. settings = self.merge_environment_settings(
  399. prep.url, proxies, stream, verify, cert
  400. )
  401. # Send the request.
  402. send_kwargs = {
  403. 'timeout': timeout,
  404. 'allow_redirects': allow_redirects,
  405. }
  406. send_kwargs.update(settings)
  407. resp = self.send(prep, **send_kwargs)
  408. return resp
  409. def get(self, url, **kwargs):
  410. r"""Sends a GET request. Returns :class:`Response` object.
  411. :param url: URL for the new :class:`Request` object.
  412. :param \*\*kwargs: Optional arguments that ``request`` takes.
  413. :rtype: requests.Response
  414. """
  415. kwargs.setdefault('allow_redirects', True)
  416. return self.request('GET', url, **kwargs)
  417. def options(self, url, **kwargs):
  418. r"""Sends a OPTIONS request. Returns :class:`Response` object.
  419. :param url: URL for the new :class:`Request` object.
  420. :param \*\*kwargs: Optional arguments that ``request`` takes.
  421. :rtype: requests.Response
  422. """
  423. kwargs.setdefault('allow_redirects', True)
  424. return self.request('OPTIONS', url, **kwargs)
  425. def head(self, url, **kwargs):
  426. r"""Sends a HEAD request. Returns :class:`Response` object.
  427. :param url: URL for the new :class:`Request` object.
  428. :param \*\*kwargs: Optional arguments that ``request`` takes.
  429. :rtype: requests.Response
  430. """
  431. kwargs.setdefault('allow_redirects', False)
  432. return self.request('HEAD', url, **kwargs)
  433. def post(self, url, data=None, json=None, **kwargs):
  434. r"""Sends a POST request. Returns :class:`Response` object.
  435. :param url: URL for the new :class:`Request` object.
  436. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
  437. :param json: (optional) json to send in the body of the :class:`Request`.
  438. :param \*\*kwargs: Optional arguments that ``request`` takes.
  439. :rtype: requests.Response
  440. """
  441. return self.request('POST', url, data=data, json=json, **kwargs)
  442. def put(self, url, data=None, **kwargs):
  443. r"""Sends a PUT request. Returns :class:`Response` object.
  444. :param url: URL for the new :class:`Request` object.
  445. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
  446. :param \*\*kwargs: Optional arguments that ``request`` takes.
  447. :rtype: requests.Response
  448. """
  449. return self.request('PUT', url, data=data, **kwargs)
  450. def patch(self, url, data=None, **kwargs):
  451. r"""Sends a PATCH request. Returns :class:`Response` object.
  452. :param url: URL for the new :class:`Request` object.
  453. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
  454. :param \*\*kwargs: Optional arguments that ``request`` takes.
  455. :rtype: requests.Response
  456. """
  457. return self.request('PATCH', url, data=data, **kwargs)
  458. def delete(self, url, **kwargs):
  459. r"""Sends a DELETE request. Returns :class:`Response` object.
  460. :param url: URL for the new :class:`Request` object.
  461. :param \*\*kwargs: Optional arguments that ``request`` takes.
  462. :rtype: requests.Response
  463. """
  464. return self.request('DELETE', url, **kwargs)
  465. def send(self, request, **kwargs):
  466. """Send a given PreparedRequest.
  467. :rtype: requests.Response
  468. """
  469. # Set defaults that the hooks can utilize to ensure they always have
  470. # the correct parameters to reproduce the previous request.
  471. kwargs.setdefault('stream', self.stream)
  472. kwargs.setdefault('verify', self.verify)
  473. kwargs.setdefault('cert', self.cert)
  474. kwargs.setdefault('proxies', self.proxies)
  475. # It's possible that users might accidentally send a Request object.
  476. # Guard against that specific failure case.
  477. if isinstance(request, Request):
  478. raise ValueError('You can only send PreparedRequests.')
  479. # Set up variables needed for resolve_redirects and dispatching of hooks
  480. allow_redirects = kwargs.pop('allow_redirects', True)
  481. stream = kwargs.get('stream')
  482. hooks = request.hooks
  483. # Get the appropriate adapter to use
  484. adapter = self.get_adapter(url=request.url)
  485. # Start time (approximately) of the request
  486. start = preferred_clock()
  487. # Send the request
  488. r = adapter.send(request, **kwargs)
  489. # Total elapsed time of the request (approximately)
  490. elapsed = preferred_clock() - start
  491. r.elapsed = timedelta(seconds=elapsed)
  492. # Response manipulation hooks
  493. r = dispatch_hook('response', hooks, r, **kwargs)
  494. # Persist cookies
  495. if r.history:
  496. # If the hooks create history then we want those cookies too
  497. for resp in r.history:
  498. extract_cookies_to_jar(self.cookies, resp.request, resp.raw)
  499. extract_cookies_to_jar(self.cookies, request, r.raw)
  500. # Redirect resolving generator.
  501. gen = self.resolve_redirects(r, request, **kwargs)
  502. # Resolve redirects if allowed.
  503. history = [resp for resp in gen] if allow_redirects else []
  504. # Shuffle things around if there's history.
  505. if history:
  506. # Insert the first (original) request at the start
  507. history.insert(0, r)
  508. # Get the last request made
  509. r = history.pop()
  510. r.history = history
  511. # If redirects aren't being followed, store the response on the Request for Response.next().
  512. if not allow_redirects:
  513. try:
  514. r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs))
  515. except StopIteration:
  516. pass
  517. if not stream:
  518. r.content
  519. return r
  520. def merge_environment_settings(self, url, proxies, stream, verify, cert):
  521. """
  522. Check the environment and merge it with some settings.
  523. :rtype: dict
  524. """
  525. # Gather clues from the surrounding environment.
  526. if self.trust_env:
  527. # Set environment's proxies.
  528. no_proxy = proxies.get('no_proxy') if proxies is not None else None
  529. env_proxies = get_environ_proxies(url, no_proxy=no_proxy)
  530. for (k, v) in env_proxies.items():
  531. proxies.setdefault(k, v)
  532. # Look for requests environment configuration and be compatible
  533. # with cURL.
  534. if verify is True or verify is None:
  535. verify = (os.environ.get('REQUESTS_CA_BUNDLE') or
  536. os.environ.get('CURL_CA_BUNDLE'))
  537. # Merge all the kwargs.
  538. proxies = merge_setting(proxies, self.proxies)
  539. stream = merge_setting(stream, self.stream)
  540. verify = merge_setting(verify, self.verify)
  541. cert = merge_setting(cert, self.cert)
  542. return {'verify': verify, 'proxies': proxies, 'stream': stream,
  543. 'cert': cert}
  544. def get_adapter(self, url):
  545. """
  546. Returns the appropriate connection adapter for the given URL.
  547. :rtype: requests.adapters.BaseAdapter
  548. """
  549. for (prefix, adapter) in self.adapters.items():
  550. if url.lower().startswith(prefix):
  551. return adapter
  552. # Nothing matches :-/
  553. raise InvalidSchema("No connection adapters were found for '%s'" % url)
  554. def close(self):
  555. """Closes all adapters and as such the session"""
  556. for v in self.adapters.values():
  557. v.close()
  558. def mount(self, prefix, adapter):
  559. """Registers a connection adapter to a prefix.
  560. Adapters are sorted in descending order by prefix length.
  561. """
  562. self.adapters[prefix] = adapter
  563. keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
  564. for key in keys_to_move:
  565. self.adapters[key] = self.adapters.pop(key)
  566. def __getstate__(self):
  567. state = dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)
  568. return state
  569. def __setstate__(self, state):
  570. for attr, value in state.items():
  571. setattr(self, attr, value)
  572. def session():
  573. """
  574. Returns a :class:`Session` for context-management.
  575. :rtype: Session
  576. """
  577. return Session()