Development of an internal social media platform with personalised dashboards for students
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

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