Debian Codegraph @

arduino-core/src/processing/app/i18n/python/requests/sessions.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 """
4 requests.session
5 ~~~~~~~~~~~~~~~~
6
7 This module provides a Session object to manage and persist settings across
8 requests (cookies, auth, proxies).
9
10 """
11 import os
12 from datetime import datetime
13
14 from .compat import cookielib
15 from .cookies import cookiejar_from_dict
16 from .models import Request, PreparedRequest
17 from .hooks import default_hooks, dispatch_hook
18 from .utils import from_key_val_list, default_headers
19 from .exceptions import TooManyRedirects, InvalidSchema
20
21 from .compat import urlparse, urljoin
22 from .adapters import HTTPAdapter
23
24 from .utils import requote_uri, get_environ_proxies, get_netrc_auth
25
26 from .status_codes import codes
27 REDIRECT_STATI = (
28 codes.moved, # 301
29 codes.found, # 302
30 codes.other, # 303
31 codes.temporary_moved, # 307
32 )
33 DEFAULT_REDIRECT_LIMIT = 30
34
35
36 def merge_kwargs(local_kwarg, default_kwarg):
37 """Merges kwarg dictionaries.
38
39 If a local key in the dictionary is set to None, it will be removed.
40 """
41
42 if default_kwarg is None:
43 return local_kwarg
44
45 if isinstance(local_kwarg, str):
46 return local_kwarg
47
48 if local_kwarg is None:
49 return default_kwarg
50
51 # Bypass if not a dictionary (e.g. timeout)
52 if not hasattr(default_kwarg, 'items'):
53 return local_kwarg
54
55 default_kwarg = from_key_val_list(default_kwarg)
56 local_kwarg = from_key_val_list(local_kwarg)
57
58 # Update new values in a case-insensitive way
59 def get_original_key(original_keys, new_key):
60 """
61 Finds the key from original_keys that case-insensitive matches new_key.
62 """
63 for original_key in original_keys:
64 if key.lower() == original_key.lower():
65 return original_key
66 return new_key
67
68 kwargs = default_kwarg.copy()
69 original_keys = kwargs.keys()
70 for key, value in local_kwarg.items():
71 kwargs[get_original_key(original_keys, key)] = value
72
73 # Remove keys that are set to None.
74 for (k, v) in local_kwarg.items():
75 if v is None:
76 del kwargs[k]
77
78 return kwargs
79
80
81 class SessionRedirectMixin(object):
82 def resolve_redirects(self, resp, req, stream=False, timeout=None,
83 verify=True, cert=None, proxies=None):
84 """Receives a Response. Returns a generator of Responses."""
85
86 i = 0
87 prepared_request = PreparedRequest()
88 prepared_request.body = req.body
89 prepared_request.headers = req.headers.copy()
90 prepared_request.hooks = req.hooks
91 prepared_request.method = req.method
92 prepared_request.url = req.url
93 cookiejar = resp.cookies
94
95 # ((resp.status_code is codes.see_other))
96 while (('location' in resp.headers and resp.status_code in REDIRECT_STATI)):
97
98 resp.content # Consume socket so it can be released
99
100 if i >= self.max_redirects:
101 raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects)
102
103 # Release the connection back into the pool.
104 resp.close()
105
106 url = resp.headers['location']
107 method = prepared_request.method
108
109 # Handle redirection without scheme (see: RFC 1808 Section 4)
110 if url.startswith('//'):
111 parsed_rurl = urlparse(resp.url)
112 url = '%s:%s' % (parsed_rurl.scheme, url)
113
114 # Facilitate non-RFC2616-compliant 'location' headers
115 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
116 if not urlparse(url).netloc:
117 # Compliant with RFC3986, we percent encode the url.
118 url = urljoin(resp.url, requote_uri(url))
119
120 prepared_request.url = url
121
122 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
123 if (resp.status_code == codes.see_other and
124 prepared_request.method != 'HEAD'):
125 method = 'GET'
126
127 # Do what the browsers do, despite standards...
128 if (resp.status_code in (codes.moved, codes.found) and
129 prepared_request.method == 'POST'):
130 method = 'GET'
131
132 prepared_request.method = method
133
134 if resp.status_code is not codes.temporary:
135 if 'Content-Length' in prepared_request.headers:
136 del prepared_request.headers['Content-Length']
137
138 prepared_request.body = None
139
140 headers = prepared_request.headers
141 try:
142 del headers['Cookie']
143 except KeyError:
144 pass
145
146 prepared_request.prepare_cookies(cookiejar)
147
148 resp = self.send(
149 prepared_request,
150 stream=stream,
151 timeout=timeout,
152 verify=verify,
153 cert=cert,
154 proxies=proxies,
155 allow_redirects=False,
156 )
157
158 cookiejar.update(resp.cookies)
159
160 i += 1
161 yield resp
162
163 resp.cookies.update(cookiejar)
164
165
166 class Session(SessionRedirectMixin):
167 """A Requests session.
168
169 Provides cookie persistience, connection-pooling, and configuration.
170
171 Basic Usage::
172
173 >>> import requests
174 >>> s = requests.Session()
175 >>> s.get('http://httpbin.org/get')
176 200
177 """
178
179 __attrs__ = [
180 'headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks',
181 'params', 'verify', 'cert', 'prefetch']
182
183 def __init__(self):
184
185 #: A case-insensitive dictionary of headers to be sent on each
186 #: :class:`Request <Request>` sent from this
187 #: :class:`Session <Session>`.
188 self.headers = default_headers()
189
190 #: Default Authentication tuple or object to attach to
191 #: :class:`Request <Request>`.
192 self.auth = None
193
194 #: Dictionary mapping protocol to the URL of the proxy (e.g.
195 #: {'http': 'foo.bar:3128'}) to be used on each
196 #: :class:`Request <Request>`.
197 self.proxies = {}
198
199 #: Event-handling hooks.
200 self.hooks = default_hooks()
201
202 #: Dictionary of querystring data to attach to each
203 #: :class:`Request <Request>`. The dictionary values may be lists for
204 #: representing multivalued query parameters.
205 self.params = {}
206
207 #: Stream response content default.
208 self.stream = False
209
210 #: SSL Verification default.
211 self.verify = True
212
213 #: SSL certificate default.
214 self.cert = None
215
216 #: Maximum number of redirects to follow.
217 self.max_redirects = DEFAULT_REDIRECT_LIMIT
218
219 #: Should we trust the environment?
220 self.trust_env = True
221
222 # Set up a CookieJar to be used by default
223 self.cookies = cookiejar_from_dict({})
224
225 # Default connection adapters.
226 self.adapters = {}
227 self.mount('http://', HTTPAdapter())
228 self.mount('https://', HTTPAdapter())
229
230 def __enter__(self):
231 return self
232
233 def __exit__(self, *args):
234 self.close()
235
236 def request(self, method, url,
237 params=None,
238 data=None,
239 headers=None,
240 cookies=None,
241 files=None,
242 auth=None,
243 timeout=None,
244 allow_redirects=True,
245 proxies=None,
246 hooks=None,
247 stream=None,
248 verify=None,
249 cert=None):
250
251 cookies = cookies or {}
252 proxies = proxies or {}
253
254 # Bootstrap CookieJar.
255 if not isinstance(cookies, cookielib.CookieJar):
256 cookies = cookiejar_from_dict(cookies)
257
258 # Merge with session cookies
259 merged_cookies = self.cookies.copy()
260 merged_cookies.update(cookies)
261 cookies = merged_cookies
262
263 # Gather clues from the surrounding environment.
264 if self.trust_env:
265 # Set environment's proxies.
266 env_proxies = get_environ_proxies(url) or {}
267 for (k, v) in env_proxies.items():
268 proxies.setdefault(k, v)
269
270 # Set environment's basic authentication.
271 if not auth:
272 auth = get_netrc_auth(url)
273
274 # Look for configuration.
275 if not verify and verify is not False:
276 verify = os.environ.get('REQUESTS_CA_BUNDLE')
277
278 # Curl compatibility.
279 if not verify and verify is not False:
280 verify = os.environ.get('CURL_CA_BUNDLE')
281
282 # Merge all the kwargs.
283 params = merge_kwargs(params, self.params)
284 headers = merge_kwargs(headers, self.headers)
285 auth = merge_kwargs(auth, self.auth)
286 proxies = merge_kwargs(proxies, self.proxies)
287 hooks = merge_kwargs(hooks, self.hooks)
288 stream = merge_kwargs(stream, self.stream)
289 verify = merge_kwargs(verify, self.verify)
290 cert = merge_kwargs(cert, self.cert)
291
292 # Create the Request.
293 req = Request()
294 req.method = method.upper()
295 req.url = url
296 req.headers = headers
297 req.files = files
298 req.data = data
299 req.params = params
300 req.auth = auth
301 req.cookies = cookies
302 req.hooks = hooks
303
304 # Prepare the Request.
305 prep = req.prepare()
306
307 # Send the request.
308 send_kwargs = {
309 'stream': stream,
310 'timeout': timeout,
311 'verify': verify,
312 'cert': cert,
313 'proxies': proxies,
314 'allow_redirects': allow_redirects,
315 'req': req,
316 }
317 resp = self.send(prep, **send_kwargs)
318
319 # Persist cookies.
320 self.cookies.update(resp.cookies)
321
322 return resp
323
324 def get(self, url, **kwargs):
325 """Sends a GET request. Returns :class:`Response` object.
326
327 :param url: URL for the new :class:`Request` object.
328 :param \*\*kwargs: Optional arguments that ``request`` takes.
329 """
330
331 kwargs.setdefault('allow_redirects', True)
332 return self.request('GET', url, **kwargs)
333
334 def options(self, url, **kwargs):
335 """Sends a OPTIONS request. Returns :class:`Response` object.
336
337 :param url: URL for the new :class:`Request` object.
338 :param \*\*kwargs: Optional arguments that ``request`` takes.
339 """
340
341 kwargs.setdefault('allow_redirects', True)
342 return self.request('OPTIONS', url, **kwargs)
343
344 def head(self, url, **kwargs):
345 """Sends a HEAD request. Returns :class:`Response` object.
346
347 :param url: URL for the new :class:`Request` object.
348 :param \*\*kwargs: Optional arguments that ``request`` takes.
349 """
350
351 kwargs.setdefault('allow_redirects', False)
352 return self.request('HEAD', url, **kwargs)
353
354 def post(self, url, data=None, **kwargs):
355 """Sends a POST request. Returns :class:`Response` object.
356
357 :param url: URL for the new :class:`Request` object.
358 :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
359 :param \*\*kwargs: Optional arguments that ``request`` takes.
360 """
361
362 return self.request('POST', url, data=data, **kwargs)
363
364 def put(self, url, data=None, **kwargs):
365 """Sends a PUT request. Returns :class:`Response` object.
366
367 :param url: URL for the new :class:`Request` object.
368 :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
369 :param \*\*kwargs: Optional arguments that ``request`` takes.
370 """
371
372 return self.request('PUT', url, data=data, **kwargs)
373
374 def patch(self, url, data=None, **kwargs):
375 """Sends a PATCH request. Returns :class:`Response` object.
376
377 :param url: URL for the new :class:`Request` object.
378 :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
379 :param \*\*kwargs: Optional arguments that ``request`` takes.
380 """
381
382 return self.request('PATCH', url, data=data, **kwargs)
383
384 def delete(self, url, **kwargs):
385 """Sends a DELETE request. Returns :class:`Response` object.
386
387 :param url: URL for the new :class:`Request` object.
388 :param \*\*kwargs: Optional arguments that ``request`` takes.
389 """
390
391 return self.request('DELETE', url, **kwargs)
392
393 def send(self, request, **kwargs):
394 """Send a given PreparedRequest."""
395 # It's possible that users might accidentally send a Request object.
396 # Guard against that specific failure case.
397 if getattr(request, 'prepare', None):
398 raise ValueError('You can only send PreparedRequests.')
399
400 # Set up variables needed for resolve_redirects and dispatching of
401 # hooks
402 allow_redirects = kwargs.pop('allow_redirects', True)
403 req = kwargs.pop('req', None)
404 stream = kwargs.get('stream', False)
405 timeout = kwargs.get('timeout')
406 verify = kwargs.get('verify')
407 cert = kwargs.get('cert')
408 proxies = kwargs.get('proxies')
409 hooks = request.hooks
410
411 # Get the appropriate adapter to use
412 adapter = self.get_adapter(url=request.url)
413
414 # Start time (approximately) of the request
415 start = datetime.utcnow()
416 # Send the request
417 r = adapter.send(request, **kwargs)
418 # Total elapsed time of the request (approximately)
419 r.elapsed = datetime.utcnow() - start
420
421 # Response manipulation hooks
422 r = dispatch_hook('response', hooks, r, **kwargs)
423
424 # Redirect resolving generator.
425 gen = self.resolve_redirects(r, request, stream=stream,
426 timeout=timeout, verify=verify, cert=cert,
427 proxies=proxies)
428
429 # Resolve redirects if allowed.
430 history = [resp for resp in gen] if allow_redirects else []
431
432 # Shuffle things around if there's history.
433 if history:
434 # Insert the first (original) request at the start
435 history.insert(0, r)
436 # Get the last request made
437 r = history.pop()
438 r.history = tuple(history)
439
440 return r
441
442 def get_adapter(self, url):
443 """Returns the appropriate connnection adapter for the given URL."""
444 for (prefix, adapter) in self.adapters.items():
445
446 if url.startswith(prefix):
447 return adapter
448
449 # Nothing matches :-/
450 raise InvalidSchema("No connection adapters were found for '%s'" % url)
451
452 def close(self):
453 """Closes all adapters and as such the session"""
454 for _, v in self.adapters.items():
455 v.close()
456
457 def mount(self, prefix, adapter):
458 """Registers a connection adapter to a prefix."""
459 self.adapters[prefix] = adapter
460
461 def __getstate__(self):
462 return dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)
463
464 def __setstate__(self, state):
465 for attr, value in state.items():
466 setattr(self, attr, value)
467
468
469 def session():
470 """Returns a :class:`Session` for context-management."""
471
472 return Session()