Plex plugin to to play various online streams (mostly Latvian).

sessions.py 25KB

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