Debian Codegraph @

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

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 """
4 requests.models
5 ~~~~~~~~~~~~~~~
6
7 This module contains the primary objects that power Requests.
8 """
9
10 import collections
11 import logging
12 import datetime
13
14 from io import BytesIO
15 from .hooks import default_hooks
16 from .structures import CaseInsensitiveDict
17
18 from .auth import HTTPBasicAuth
19 from .cookies import cookiejar_from_dict, get_cookie_header
20 from .packages.urllib3.filepost import encode_multipart_formdata
21 from .exceptions import HTTPError, RequestException, MissingSchema, InvalidURL
22 from .utils import (
23 stream_untransfer, guess_filename, requote_uri,
24 stream_decode_response_unicode, to_key_val_list, parse_header_links,
25 iter_slices, guess_json_utf, super_len)
26 from .compat import (
27 cookielib, urlparse, urlunparse, urlsplit, urlencode, str, bytes, StringIO,
28 is_py2, chardet, json, builtin_str, basestring)
29
30 CONTENT_CHUNK_SIZE = 10 * 1024
31 ITER_CHUNK_SIZE = 512
32
33 log = logging.getLogger(__name__)
34
35
36 class RequestEncodingMixin(object):
37 @property
38 def path_url(self):
39 """Build the path URL to use."""
40
41 url = []
42
43 p = urlsplit(self.url)
44
45 path = p.path
46 if not path:
47 path = '/'
48
49 url.append(path)
50
51 query = p.query
52 if query:
53 url.append('?')
54 url.append(query)
55
56 return ''.join(url)
57
58 @staticmethod
59 def _encode_params(data):
60 """Encode parameters in a piece of data.
61
62 Will successfully encode parameters when passed as a dict or a list of
63 2-tuples. Order is retained if data is a list of 2-tuples but abritrary
64 if parameters are supplied as a dict.
65 """
66
67 if isinstance(data, (str, bytes)):
68 return data
69 elif hasattr(data, 'read'):
70 return data
71 elif hasattr(data, '__iter__'):
72 result = []
73 for k, vs in to_key_val_list(data):
74 if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
75 vs = [vs]
76 for v in vs:
77 if v is not None:
78 result.append(
79 (k.encode('utf-8') if isinstance(k, str) else k,
80 v.encode('utf-8') if isinstance(v, str) else v))
81 return urlencode(result, doseq=True)
82 else:
83 return data
84
85 @staticmethod
86 def _encode_files(files, data):
87 """Build the body for a multipart/form-data request.
88
89 Will successfully encode files when passed as a dict or a list of
90 2-tuples. Order is retained if data is a list of 2-tuples but abritrary
91 if parameters are supplied as a dict.
92
93 """
94 if (not files) or isinstance(data, str):
95 return None
96
97 new_fields = []
98 fields = to_key_val_list(data or {})
99 files = to_key_val_list(files or {})
100
101 for field, val in fields:
102 if isinstance(val, list):
103 for v in val:
104 new_fields.append((field, builtin_str(v)))
105 else:
106 new_fields.append((field, builtin_str(val)))
107
108 for (k, v) in files:
109 # support for explicit filename
110 ft = None
111 if isinstance(v, (tuple, list)):
112 if len(v) == 2:
113 fn, fp = v
114 else:
115 fn, fp, ft = v
116 else:
117 fn = guess_filename(v) or k
118 fp = v
119 if isinstance(fp, str):
120 fp = StringIO(fp)
121 if isinstance(fp, bytes):
122 fp = BytesIO(fp)
123
124 if ft:
125 new_v = (fn, fp.read(), ft)
126 else:
127 new_v = (fn, fp.read())
128 new_fields.append((k, new_v))
129
130 body, content_type = encode_multipart_formdata(new_fields)
131
132 return body, content_type
133
134
135 class RequestHooksMixin(object):
136 def register_hook(self, event, hook):
137 """Properly register a hook."""
138
139 if isinstance(hook, collections.Callable):
140 self.hooks[event].append(hook)
141 elif hasattr(hook, '__iter__'):
142 self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))
143
144 def deregister_hook(self, event, hook):
145 """Deregister a previously registered hook.
146 Returns True if the hook existed, False if not.
147 """
148
149 try:
150 self.hooks[event].remove(hook)
151 return True
152 except ValueError:
153 return False
154
155
156 class Request(RequestHooksMixin):
157 """A user-created :class:`Request <Request>` object.
158
159 Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.
160
161 :param method: HTTP method to use.
162 :param url: URL to send.
163 :param headers: dictionary of headers to send.
164 :param files: dictionary of {filename: fileobject} files to multipart upload.
165 :param data: the body to attach the request. If a dictionary is provided, form-encoding will take place.
166 :param params: dictionary of URL parameters to append to the URL.
167 :param auth: Auth handler or (user, pass) tuple.
168 :param cookies: dictionary or CookieJar of cookies to attach to this request.
169 :param hooks: dictionary of callback hooks, for internal usage.
170
171 Usage::
172
173 >>> import requests
174 >>> req = requests.Request('GET', 'http://httpbin.org/get')
175 >>> req.prepare()
176 <PreparedRequest [GET]>
177
178 """
179 def __init__(self,
180 method=None,
181 url=None,
182 headers=None,
183 files=None,
184 data=dict(),
185 params=dict(),
186 auth=None,
187 cookies=None,
188 hooks=None):
189
190 # Default empty dicts for dict params.
191 data = [] if data is None else data
192 files = [] if files is None else files
193 headers = {} if headers is None else headers
194 params = {} if params is None else params
195 hooks = {} if hooks is None else hooks
196
197 self.hooks = default_hooks()
198 for (k, v) in list(hooks.items()):
199 self.register_hook(event=k, hook=v)
200
201 self.method = method
202 self.url = url
203 self.headers = headers
204 self.files = files
205 self.data = data
206 self.params = params
207 self.auth = auth
208 self.cookies = cookies
209 self.hooks = hooks
210
211 def __repr__(self):
212 return '<Request [%s]>' % (self.method)
213
214 def prepare(self):
215 """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""
216 p = PreparedRequest()
217
218 p.prepare_method(self.method)
219 p.prepare_url(self.url, self.params)
220 p.prepare_headers(self.headers)
221 p.prepare_cookies(self.cookies)
222 p.prepare_body(self.data, self.files)
223 # Note that prepare_auth must be last to enable authentication schemes
224 # such as OAuth to work on a fully prepared request.
225 p.prepare_auth(self.auth)
226 # This MUST go after prepare_auth. Authenticators could add a hook
227 p.prepare_hooks(self.hooks)
228
229 return p
230
231
232 class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
233 """The fully mutable :class:`PreparedRequest <PreparedRequest>` object,
234 containing the exact bytes that will be sent to the server.
235
236 Generated from either a :class:`Request <Request>` object or manually.
237
238 Usage::
239
240 >>> import requests
241 >>> req = requests.Request('GET', 'http://httpbin.org/get')
242 >>> r = req.prepare()
243 <PreparedRequest [GET]>
244
245 >>> s = requests.Session()
246 >>> s.send(r)
247 <Response [200]>
248
249 """
250
251 def __init__(self):
252 #: HTTP verb to send to the server.
253 self.method = None
254 #: HTTP URL to send the request to.
255 self.url = None
256 #: dictionary of HTTP headers.
257 self.headers = None
258 #: request body to send to the server.
259 self.body = None
260 #: dictionary of callback hooks, for internal usage.
261 self.hooks = default_hooks()
262
263 def __repr__(self):
264 return '<PreparedRequest [%s]>' % (self.method)
265
266 def prepare_method(self, method):
267 """Prepares the given HTTP method."""
268 self.method = method
269 if self.method is not None:
270 self.method = self.method.upper()
271
272 def prepare_url(self, url, params):
273 """Prepares the given HTTP URL."""
274 #: Accept objects that have string representations.
275 try:
276 url = unicode(url)
277 except NameError:
278 # We're on Python 3.
279 url = str(url)
280 except UnicodeDecodeError:
281 pass
282
283 # Support for unicode domain names and paths.
284 scheme, netloc, path, _params, query, fragment = urlparse(url)
285
286 if not (scheme and netloc):
287 raise MissingSchema("Invalid URL %r: No schema supplied" % url)
288
289 try:
290 netloc = netloc.encode('idna').decode('utf-8')
291 except UnicodeError:
292 raise InvalidURL('URL has an invalid label.')
293
294 # Bare domains aren't valid URLs.
295 if not path:
296 path = '/'
297
298 if is_py2:
299 if isinstance(scheme, str):
300 scheme = scheme.encode('utf-8')
301 if isinstance(netloc, str):
302 netloc = netloc.encode('utf-8')
303 if isinstance(path, str):
304 path = path.encode('utf-8')
305 if isinstance(_params, str):
306 _params = _params.encode('utf-8')
307 if isinstance(query, str):
308 query = query.encode('utf-8')
309 if isinstance(fragment, str):
310 fragment = fragment.encode('utf-8')
311
312 enc_params = self._encode_params(params)
313 if enc_params:
314 if query:
315 query = '%s&%s' % (query, enc_params)
316 else:
317 query = enc_params
318
319 url = requote_uri(urlunparse([scheme, netloc, path, _params, query, fragment]))
320 self.url = url
321
322 def prepare_headers(self, headers):
323 """Prepares the given HTTP headers."""
324
325 if headers:
326 headers = dict((name.encode('ascii'), value) for name, value in headers.items())
327 self.headers = CaseInsensitiveDict(headers)
328 else:
329 self.headers = CaseInsensitiveDict()
330
331 def prepare_body(self, data, files):
332 """Prepares the given HTTP body data."""
333
334 # Check if file, fo, generator, iterator.
335 # If not, run through normal process.
336
337 # Nottin' on you.
338 body = None
339 content_type = None
340 length = None
341 is_stream = False
342
343 is_stream = all([
344 hasattr(data, '__iter__'),
345 not isinstance(data, basestring),
346 not isinstance(data, list),
347 not isinstance(data, dict)
348 ])
349
350 try:
351 length = str(super_len(data))
352 except (TypeError, AttributeError):
353 length = False
354
355 if is_stream:
356 body = data
357
358 if files:
359 raise NotImplementedError('Streamed bodies and files are mutually exclusive.')
360
361 if length:
362 self.headers['Content-Length'] = length
363 else:
364 self.headers['Transfer-Encoding'] = 'chunked'
365 # Check if file, fo, generator, iterator.
366 # If not, run through normal process.
367
368 else:
369 # Multi-part file uploads.
370 if files:
371 (body, content_type) = self._encode_files(files, data)
372 else:
373 if data:
374 body = self._encode_params(data)
375 if isinstance(data, str) or isinstance(data, builtin_str) or hasattr(data, 'read'):
376 content_type = None
377 else:
378 content_type = 'application/x-www-form-urlencoded'
379
380 self.prepare_content_length(body)
381
382 # Add content-type if it wasn't explicitly provided.
383 if (content_type) and (not 'content-type' in self.headers):
384 self.headers['Content-Type'] = content_type
385
386 self.body = body
387
388 def prepare_content_length(self, body):
389 if hasattr(body, 'seek') and hasattr(body, 'tell'):
390 body.seek(0, 2)
391 self.headers['Content-Length'] = str(body.tell())
392 body.seek(0, 0)
393 elif body is not None:
394 self.headers['Content-Length'] = str(len(body))
395 elif self.method not in ('GET', 'HEAD'):
396 self.headers['Content-Length'] = '0'
397
398 def prepare_auth(self, auth):
399 """Prepares the given HTTP auth data."""
400 if auth:
401 if isinstance(auth, tuple) and len(auth) == 2:
402 # special-case basic HTTP auth
403 auth = HTTPBasicAuth(*auth)
404
405 # Allow auth to make its changes.
406 r = auth(self)
407
408 # Update self to reflect the auth changes.
409 self.__dict__.update(r.__dict__)
410
411 # Recompute Content-Length
412 self.prepare_content_length(self.body)
413
414 def prepare_cookies(self, cookies):
415 """Prepares the given HTTP cookie data."""
416
417 if isinstance(cookies, cookielib.CookieJar):
418 cookies = cookies
419 else:
420 cookies = cookiejar_from_dict(cookies)
421
422 if 'cookie' not in self.headers:
423 cookie_header = get_cookie_header(cookies, self)
424 if cookie_header is not None:
425 self.headers['Cookie'] = cookie_header
426
427 def prepare_hooks(self, hooks):
428 """Prepares the given hooks."""
429 for event in hooks:
430 self.register_hook(event, hooks[event])
431
432
433 class Response(object):
434 """The :class:`Response <Response>` object, which contains a
435 server's response to an HTTP request.
436 """
437
438 def __init__(self):
439 super(Response, self).__init__()
440
441 self._content = False
442 self._content_consumed = False
443
444 #: Integer Code of responded HTTP Status.
445 self.status_code = None
446
447 #: Case-insensitive Dictionary of Response Headers.
448 #: For example, ``headers['content-encoding']`` will return the
449 #: value of a ``'Content-Encoding'`` response header.
450 self.headers = CaseInsensitiveDict()
451
452 #: File-like object representation of response (for advanced usage).
453 #: Requires that ``stream=True` on the request.
454 # This requirement does not apply for use internally to Requests.
455 self.raw = None
456
457 #: Final URL location of Response.
458 self.url = None
459
460 #: Encoding to decode with when accessing r.text.
461 self.encoding = None
462
463 #: A list of :class:`Response <Response>` objects from
464 #: the history of the Request. Any redirect responses will end
465 #: up here. The list is sorted from the oldest to the most recent request.
466 self.history = []
467
468 self.reason = None
469
470 #: A CookieJar of Cookies the server sent back.
471 self.cookies = cookiejar_from_dict({})
472
473 #: The amount of time elapsed between sending the request
474 #: and the arrival of the response (as a timedelta)
475 self.elapsed = datetime.timedelta(0)
476
477 def __repr__(self):
478 return '<Response [%s]>' % (self.status_code)
479
480 def __bool__(self):
481 """Returns true if :attr:`status_code` is 'OK'."""
482 return self.ok
483
484 def __nonzero__(self):
485 """Returns true if :attr:`status_code` is 'OK'."""
486 return self.ok
487
488 def __iter__(self):
489 """Allows you to use a response as an iterator."""
490 return self.iter_content(128)
491
492 @property
493 def ok(self):
494 try:
495 self.raise_for_status()
496 except RequestException:
497 return False
498 return True
499
500 @property
501 def apparent_encoding(self):
502 """The apparent encoding, provided by the lovely Charade library
503 (Thanks, Ian!)."""
504 return chardet.detect(self.content)['encoding']
505
506 def iter_content(self, chunk_size=1, decode_unicode=False):
507 """Iterates over the response data. This avoids reading the content
508 at once into memory for large responses. The chunk size is the number
509 of bytes it should read into memory. This is not necessarily the
510 length of each item returned as decoding can take place.
511 """
512 if self._content_consumed:
513 # simulate reading small chunks of the content
514 return iter_slices(self._content, chunk_size)
515
516 def generate():
517 while 1:
518 chunk = self.raw.read(chunk_size)
519 if not chunk:
520 break
521 yield chunk
522 self._content_consumed = True
523
524 gen = stream_untransfer(generate(), self)
525
526 if decode_unicode:
527 gen = stream_decode_response_unicode(gen, self)
528
529 return gen
530
531 def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None):
532 """Iterates over the response data, one line at a time. This
533 avoids reading the content at once into memory for large
534 responses.
535 """
536
537 pending = None
538
539 for chunk in self.iter_content(chunk_size=chunk_size,
540 decode_unicode=decode_unicode):
541
542 if pending is not None:
543 chunk = pending + chunk
544 lines = chunk.splitlines()
545
546 if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
547 pending = lines.pop()
548 else:
549 pending = None
550
551 for line in lines:
552 yield line
553
554 if pending is not None:
555 yield pending
556
557 @property
558 def content(self):
559 """Content of the response, in bytes."""
560
561 if self._content is False:
562 # Read the contents.
563 try:
564 if self._content_consumed:
565 raise RuntimeError(
566 'The content for this response was already consumed')
567
568 if self.status_code is 0:
569 self._content = None
570 else:
571 self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
572
573 except AttributeError:
574 self._content = None
575
576 self._content_consumed = True
577 # don't need to release the connection; that's been handled by urllib3
578 # since we exhausted the data.
579 return self._content
580
581 @property
582 def text(self):
583 """Content of the response, in unicode.
584
585 if Response.encoding is None and chardet module is available, encoding
586 will be guessed.
587 """
588
589 # Try charset from content-type
590 content = None
591 encoding = self.encoding
592
593 if not self.content:
594 return str('')
595
596 # Fallback to auto-detected encoding.
597 if self.encoding is None:
598 encoding = self.apparent_encoding
599
600 # Decode unicode from given encoding.
601 try:
602 content = str(self.content, encoding, errors='replace')
603 except (LookupError, TypeError):
604 # A LookupError is raised if the encoding was not found which could
605 # indicate a misspelling or similar mistake.
606 #
607 # A TypeError can be raised if encoding is None
608 #
609 # So we try blindly encoding.
610 content = str(self.content, errors='replace')
611
612 return content
613
614 def json(self, **kwargs):
615 """Returns the json-encoded content of a response, if any.
616
617 :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
618 """
619
620 if not self.encoding and len(self.content) > 3:
621 # No encoding set. JSON RFC 4627 section 3 states we should expect
622 # UTF-8, -16 or -32. Detect which one to use; If the detection or
623 # decoding fails, fall back to `self.text` (using chardet to make
624 # a best guess).
625 encoding = guess_json_utf(self.content)
626 if encoding is not None:
627 return json.loads(self.content.decode(encoding), **kwargs)
628 return json.loads(self.text or self.content, **kwargs)
629
630 @property
631 def links(self):
632 """Returns the parsed header links of the response, if any."""
633
634 header = self.headers['link']
635
636 # l = MultiDict()
637 l = {}
638
639 if header:
640 links = parse_header_links(header)
641
642 for link in links:
643 key = link.get('rel') or link.get('url')
644 l[key] = link
645
646 return l
647
648 def raise_for_status(self):
649 """Raises stored :class:`HTTPError`, if one occurred."""
650
651 http_error_msg = ''
652
653 if 400 <= self.status_code < 500:
654 http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason)
655
656 elif 500 <= self.status_code < 600:
657 http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason)
658
659 if http_error_msg:
660 raise HTTPError(http_error_msg, response=self)
661
662 def close(self):
663 return self.raw.release_conn()