sessions.py 27 KB

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