sessions.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. from collections import Mapping
  10. from datetime import datetime
  11. from .compat import cookielib, OrderedDict, urljoin, urlparse
  12. from .cookies import cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar
  13. from .models import Request, PreparedRequest
  14. from .hooks import default_hooks, dispatch_hook
  15. from .utils import to_key_val_list, default_headers
  16. from .exceptions import TooManyRedirects, InvalidSchema
  17. from .structures import CaseInsensitiveDict
  18. from .adapters import HTTPAdapter
  19. from .utils import requote_uri, get_environ_proxies, get_netrc_auth
  20. from .status_codes import codes
  21. REDIRECT_STATI = (
  22. codes.moved, # 301
  23. codes.found, # 302
  24. codes.other, # 303
  25. codes.temporary_moved, # 307
  26. )
  27. DEFAULT_REDIRECT_LIMIT = 30
  28. def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
  29. """
  30. Determines appropriate setting for a given request, taking into account the
  31. explicit setting on that request, and the setting in the session. If a
  32. setting is a dictionary, they will be merged together using `dict_class`
  33. """
  34. if session_setting is None:
  35. return request_setting
  36. if request_setting is None:
  37. return session_setting
  38. # Bypass if not a dictionary (e.g. verify)
  39. if not (
  40. isinstance(session_setting, Mapping) and
  41. isinstance(request_setting, Mapping)
  42. ):
  43. return request_setting
  44. merged_setting = dict_class(to_key_val_list(session_setting))
  45. merged_setting.update(to_key_val_list(request_setting))
  46. # Remove keys that are set to None.
  47. for (k, v) in request_setting.items():
  48. if v is None:
  49. del merged_setting[k]
  50. return merged_setting
  51. class SessionRedirectMixin(object):
  52. def resolve_redirects(self, resp, req, stream=False, timeout=None,
  53. verify=True, cert=None, proxies=None):
  54. """Receives a Response. Returns a generator of Responses."""
  55. i = 0
  56. # ((resp.status_code is codes.see_other))
  57. while (('location' in resp.headers and resp.status_code in REDIRECT_STATI)):
  58. prepared_request = req.copy()
  59. resp.content # Consume socket so it can be released
  60. if i >= self.max_redirects:
  61. raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects)
  62. # Release the connection back into the pool.
  63. resp.close()
  64. url = resp.headers['location']
  65. method = req.method
  66. # Handle redirection without scheme (see: RFC 1808 Section 4)
  67. if url.startswith('//'):
  68. parsed_rurl = urlparse(resp.url)
  69. url = '%s:%s' % (parsed_rurl.scheme, url)
  70. # The scheme should be lower case...
  71. if '://' in url:
  72. scheme, uri = url.split('://', 1)
  73. url = '%s://%s' % (scheme.lower(), uri)
  74. # Facilitate non-RFC2616-compliant 'location' headers
  75. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
  76. # Compliant with RFC3986, we percent encode the url.
  77. if not urlparse(url).netloc:
  78. url = urljoin(resp.url, requote_uri(url))
  79. else:
  80. url = requote_uri(url)
  81. prepared_request.url = url
  82. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
  83. if (resp.status_code == codes.see_other and
  84. method != 'HEAD'):
  85. method = 'GET'
  86. # Do what the browsers do, despite standards...
  87. if (resp.status_code in (codes.moved, codes.found) and
  88. method not in ('GET', 'HEAD')):
  89. method = 'GET'
  90. prepared_request.method = method
  91. # https://github.com/kennethreitz/requests/issues/1084
  92. if resp.status_code not in (codes.temporary, codes.resume):
  93. if 'Content-Length' in prepared_request.headers:
  94. del prepared_request.headers['Content-Length']
  95. prepared_request.body = None
  96. headers = prepared_request.headers
  97. try:
  98. del headers['Cookie']
  99. except KeyError:
  100. pass
  101. prepared_request.prepare_cookies(self.cookies)
  102. resp = self.send(
  103. prepared_request,
  104. stream=stream,
  105. timeout=timeout,
  106. verify=verify,
  107. cert=cert,
  108. proxies=proxies,
  109. allow_redirects=False,
  110. )
  111. extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)
  112. i += 1
  113. yield resp
  114. class Session(SessionRedirectMixin):
  115. """A Requests session.
  116. Provides cookie persistence, connection-pooling, and configuration.
  117. Basic Usage::
  118. >>> import requests
  119. >>> s = requests.Session()
  120. >>> s.get('http://httpbin.org/get')
  121. 200
  122. """
  123. __attrs__ = [
  124. 'headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks',
  125. 'params', 'verify', 'cert', 'prefetch', 'adapters', 'stream',
  126. 'trust_env', 'max_redirects']
  127. def __init__(self):
  128. #: A case-insensitive dictionary of headers to be sent on each
  129. #: :class:`Request <Request>` sent from this
  130. #: :class:`Session <Session>`.
  131. self.headers = default_headers()
  132. #: Default Authentication tuple or object to attach to
  133. #: :class:`Request <Request>`.
  134. self.auth = None
  135. #: Dictionary mapping protocol to the URL of the proxy (e.g.
  136. #: {'http': 'foo.bar:3128'}) to be used on each
  137. #: :class:`Request <Request>`.
  138. self.proxies = {}
  139. #: Event-handling hooks.
  140. self.hooks = default_hooks()
  141. #: Dictionary of querystring data to attach to each
  142. #: :class:`Request <Request>`. The dictionary values may be lists for
  143. #: representing multivalued query parameters.
  144. self.params = {}
  145. #: Stream response content default.
  146. self.stream = False
  147. #: SSL Verification default.
  148. self.verify = True
  149. #: SSL certificate default.
  150. self.cert = None
  151. #: Maximum number of redirects allowed. If the request exceeds this
  152. #: limit, a :class:`TooManyRedirects` exception is raised.
  153. self.max_redirects = DEFAULT_REDIRECT_LIMIT
  154. #: Should we trust the environment?
  155. self.trust_env = True
  156. #: A CookieJar containing all currently outstanding cookies set on this
  157. #: session. By default it is a
  158. #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but
  159. #: may be any other ``cookielib.CookieJar`` compatible object.
  160. self.cookies = cookiejar_from_dict({})
  161. # Default connection adapters.
  162. self.adapters = OrderedDict()
  163. self.mount('https://', HTTPAdapter())
  164. self.mount('http://', HTTPAdapter())
  165. def __enter__(self):
  166. return self
  167. def __exit__(self, *args):
  168. self.close()
  169. def prepare_request(self, request):
  170. """Constructs a :class:`PreparedRequest <PreparedRequest>` for
  171. transmission and returns it. The :class:`PreparedRequest` has settings
  172. merged from the :class:`Request <Request>` instance and those of the
  173. :class:`Session`.
  174. :param request: :class:`Request` instance to prepare with this
  175. session's settings.
  176. """
  177. cookies = request.cookies or {}
  178. # Bootstrap CookieJar.
  179. if not isinstance(cookies, cookielib.CookieJar):
  180. cookies = cookiejar_from_dict(cookies)
  181. # Merge with session cookies
  182. merged_cookies = RequestsCookieJar()
  183. merged_cookies.update(self.cookies)
  184. merged_cookies.update(cookies)
  185. # Set environment's basic authentication if not explicitly set.
  186. auth = request.auth
  187. if self.trust_env and not auth and not self.auth:
  188. auth = get_netrc_auth(request.url)
  189. p = PreparedRequest()
  190. p.prepare(
  191. method=request.method.upper(),
  192. url=request.url,
  193. files=request.files,
  194. data=request.data,
  195. headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict),
  196. params=merge_setting(request.params, self.params),
  197. auth=merge_setting(auth, self.auth),
  198. cookies=merged_cookies,
  199. hooks=merge_setting(request.hooks, self.hooks),
  200. )
  201. return p
  202. def request(self, method, url,
  203. params=None,
  204. data=None,
  205. headers=None,
  206. cookies=None,
  207. files=None,
  208. auth=None,
  209. timeout=None,
  210. allow_redirects=True,
  211. proxies=None,
  212. hooks=None,
  213. stream=None,
  214. verify=None,
  215. cert=None):
  216. """Constructs a :class:`Request <Request>`, prepares it and sends it.
  217. Returns :class:`Response <Response>` object.
  218. :param method: method for the new :class:`Request` object.
  219. :param url: URL for the new :class:`Request` object.
  220. :param params: (optional) Dictionary or bytes to be sent in the query
  221. string for the :class:`Request`.
  222. :param data: (optional) Dictionary or bytes to send in the body of the
  223. :class:`Request`.
  224. :param headers: (optional) Dictionary of HTTP Headers to send with the
  225. :class:`Request`.
  226. :param cookies: (optional) Dict or CookieJar object to send with the
  227. :class:`Request`.
  228. :param files: (optional) Dictionary of 'filename': file-like-objects
  229. for multipart encoding upload.
  230. :param auth: (optional) Auth tuple or callable to enable
  231. Basic/Digest/Custom HTTP Auth.
  232. :param timeout: (optional) Float describing the timeout of the
  233. request.
  234. :param allow_redirects: (optional) Boolean. Set to True by default.
  235. :param proxies: (optional) Dictionary mapping protocol to the URL of
  236. the proxy.
  237. :param stream: (optional) whether to immediately download the response
  238. content. Defaults to ``False``.
  239. :param verify: (optional) if ``True``, the SSL cert will be verified.
  240. A CA_BUNDLE path can also be provided.
  241. :param cert: (optional) if String, path to ssl client cert file (.pem).
  242. If Tuple, ('cert', 'key') pair.
  243. """
  244. # Create the Request.
  245. req = Request(
  246. method = method.upper(),
  247. url = url,
  248. headers = headers,
  249. files = files,
  250. data = data or {},
  251. params = params or {},
  252. auth = auth,
  253. cookies = cookies,
  254. hooks = hooks,
  255. )
  256. prep = self.prepare_request(req)
  257. proxies = proxies or {}
  258. # Gather clues from the surrounding environment.
  259. if self.trust_env:
  260. # Set environment's proxies.
  261. env_proxies = get_environ_proxies(url) or {}
  262. for (k, v) in env_proxies.items():
  263. proxies.setdefault(k, v)
  264. # Look for configuration.
  265. if not verify and verify is not False:
  266. verify = os.environ.get('REQUESTS_CA_BUNDLE')
  267. # Curl compatibility.
  268. if not verify and verify is not False:
  269. verify = os.environ.get('CURL_CA_BUNDLE')
  270. # Merge all the kwargs.
  271. proxies = merge_setting(proxies, self.proxies)
  272. stream = merge_setting(stream, self.stream)
  273. verify = merge_setting(verify, self.verify)
  274. cert = merge_setting(cert, self.cert)
  275. # Send the request.
  276. send_kwargs = {
  277. 'stream': stream,
  278. 'timeout': timeout,
  279. 'verify': verify,
  280. 'cert': cert,
  281. 'proxies': proxies,
  282. 'allow_redirects': allow_redirects,
  283. }
  284. resp = self.send(prep, **send_kwargs)
  285. return resp
  286. def get(self, url, **kwargs):
  287. """Sends a GET request. Returns :class:`Response` object.
  288. :param url: URL for the new :class:`Request` object.
  289. :param \*\*kwargs: Optional arguments that ``request`` takes.
  290. """
  291. kwargs.setdefault('allow_redirects', True)
  292. return self.request('GET', url, **kwargs)
  293. def options(self, url, **kwargs):
  294. """Sends a OPTIONS request. Returns :class:`Response` object.
  295. :param url: URL for the new :class:`Request` object.
  296. :param \*\*kwargs: Optional arguments that ``request`` takes.
  297. """
  298. kwargs.setdefault('allow_redirects', True)
  299. return self.request('OPTIONS', url, **kwargs)
  300. def head(self, url, **kwargs):
  301. """Sends a HEAD request. Returns :class:`Response` object.
  302. :param url: URL for the new :class:`Request` object.
  303. :param \*\*kwargs: Optional arguments that ``request`` takes.
  304. """
  305. kwargs.setdefault('allow_redirects', False)
  306. return self.request('HEAD', url, **kwargs)
  307. def post(self, url, data=None, **kwargs):
  308. """Sends a POST request. Returns :class:`Response` object.
  309. :param url: URL for the new :class:`Request` object.
  310. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
  311. :param \*\*kwargs: Optional arguments that ``request`` takes.
  312. """
  313. return self.request('POST', url, data=data, **kwargs)
  314. def put(self, url, data=None, **kwargs):
  315. """Sends a PUT request. Returns :class:`Response` object.
  316. :param url: URL for the new :class:`Request` object.
  317. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
  318. :param \*\*kwargs: Optional arguments that ``request`` takes.
  319. """
  320. return self.request('PUT', url, data=data, **kwargs)
  321. def patch(self, url, data=None, **kwargs):
  322. """Sends a PATCH request. Returns :class:`Response` object.
  323. :param url: URL for the new :class:`Request` object.
  324. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
  325. :param \*\*kwargs: Optional arguments that ``request`` takes.
  326. """
  327. return self.request('PATCH', url, data=data, **kwargs)
  328. def delete(self, url, **kwargs):
  329. """Sends a DELETE request. Returns :class:`Response` object.
  330. :param url: URL for the new :class:`Request` object.
  331. :param \*\*kwargs: Optional arguments that ``request`` takes.
  332. """
  333. return self.request('DELETE', url, **kwargs)
  334. def send(self, request, **kwargs):
  335. """Send a given PreparedRequest."""
  336. # Set defaults that the hooks can utilize to ensure they always have
  337. # the correct parameters to reproduce the previous request.
  338. kwargs.setdefault('stream', self.stream)
  339. kwargs.setdefault('verify', self.verify)
  340. kwargs.setdefault('cert', self.cert)
  341. kwargs.setdefault('proxies', self.proxies)
  342. # It's possible that users might accidentally send a Request object.
  343. # Guard against that specific failure case.
  344. if not isinstance(request, PreparedRequest):
  345. raise ValueError('You can only send PreparedRequests.')
  346. # Set up variables needed for resolve_redirects and dispatching of
  347. # hooks
  348. allow_redirects = kwargs.pop('allow_redirects', True)
  349. stream = kwargs.get('stream')
  350. timeout = kwargs.get('timeout')
  351. verify = kwargs.get('verify')
  352. cert = kwargs.get('cert')
  353. proxies = kwargs.get('proxies')
  354. hooks = request.hooks
  355. # Get the appropriate adapter to use
  356. adapter = self.get_adapter(url=request.url)
  357. # Start time (approximately) of the request
  358. start = datetime.utcnow()
  359. # Send the request
  360. r = adapter.send(request, **kwargs)
  361. # Total elapsed time of the request (approximately)
  362. r.elapsed = datetime.utcnow() - start
  363. # Response manipulation hooks
  364. r = dispatch_hook('response', hooks, r, **kwargs)
  365. # Persist cookies
  366. if r.history:
  367. # If the hooks create history then we want those cookies too
  368. for resp in r.history:
  369. extract_cookies_to_jar(self.cookies, resp.request, resp.raw)
  370. extract_cookies_to_jar(self.cookies, request, r.raw)
  371. # Redirect resolving generator.
  372. gen = self.resolve_redirects(r, request, stream=stream,
  373. timeout=timeout, verify=verify, cert=cert,
  374. proxies=proxies)
  375. # Resolve redirects if allowed.
  376. history = [resp for resp in gen] if allow_redirects else []
  377. # Shuffle things around if there's history.
  378. if history:
  379. # Insert the first (original) request at the start
  380. history.insert(0, r)
  381. # Get the last request made
  382. r = history.pop()
  383. r.history = tuple(history)
  384. return r
  385. def get_adapter(self, url):
  386. """Returns the appropriate connnection adapter for the given URL."""
  387. for (prefix, adapter) in self.adapters.items():
  388. if url.lower().startswith(prefix):
  389. return adapter
  390. # Nothing matches :-/
  391. raise InvalidSchema("No connection adapters were found for '%s'" % url)
  392. def close(self):
  393. """Closes all adapters and as such the session"""
  394. for v in self.adapters.values():
  395. v.close()
  396. def mount(self, prefix, adapter):
  397. """Registers a connection adapter to a prefix.
  398. Adapters are sorted in descending order by key length."""
  399. self.adapters[prefix] = adapter
  400. keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
  401. for key in keys_to_move:
  402. self.adapters[key] = self.adapters.pop(key)
  403. def __getstate__(self):
  404. return dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)
  405. def __setstate__(self, state):
  406. for attr, value in state.items():
  407. setattr(self, attr, value)
  408. def session():
  409. """Returns a :class:`Session` for context-management."""
  410. return Session()