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 29KB

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