Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/requests/models.py: 19%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2requests.models
3~~~~~~~~~~~~~~~
5This module contains the primary objects that power Requests.
6"""
8import datetime
10# Import encoding now, to avoid implicit import later.
11# Implicit import within threads may cause LookupError when standard library is in a ZIP,
12# such as in Embedded Python. See https://github.com/psf/requests/issues/3578.
13import encodings.idna # noqa: F401
14from io import UnsupportedOperation
16from urllib3.exceptions import (
17 DecodeError,
18 LocationParseError,
19 ProtocolError,
20 ReadTimeoutError,
21 SSLError,
22)
23from urllib3.fields import RequestField
24from urllib3.filepost import encode_multipart_formdata
25from urllib3.util import parse_url
27from ._internal_utils import to_native_string, unicode_is_ascii
28from .auth import HTTPBasicAuth
29from .compat import (
30 Callable,
31 JSONDecodeError,
32 Mapping,
33 basestring,
34 builtin_str,
35 chardet,
36 cookielib,
37)
38from .compat import json as complexjson
39from .compat import urlencode, urlsplit, urlunparse
40from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header
41from .exceptions import (
42 ChunkedEncodingError,
43 ConnectionError,
44 ContentDecodingError,
45 HTTPError,
46 InvalidJSONError,
47 InvalidURL,
48)
49from .exceptions import JSONDecodeError as RequestsJSONDecodeError
50from .exceptions import MissingSchema
51from .exceptions import SSLError as RequestsSSLError
52from .exceptions import StreamConsumedError
53from .hooks import default_hooks
54from .status_codes import codes
55from .structures import CaseInsensitiveDict
56from .utils import (
57 check_header_validity,
58 get_auth_from_url,
59 guess_filename,
60 guess_json_utf,
61 iter_slices,
62 parse_header_links,
63 requote_uri,
64 stream_decode_response_unicode,
65 super_len,
66 to_key_val_list,
67)
69#: The set of HTTP status codes that indicate an automatically
70#: processable redirect.
71REDIRECT_STATI = (
72 codes.moved, # 301
73 codes.found, # 302
74 codes.other, # 303
75 codes.temporary_redirect, # 307
76 codes.permanent_redirect, # 308
77)
79DEFAULT_REDIRECT_LIMIT = 30
80CONTENT_CHUNK_SIZE = 10 * 1024
81ITER_CHUNK_SIZE = 512
84class RequestEncodingMixin:
85 @property
86 def path_url(self):
87 """Build the path URL to use."""
89 url = []
91 p = urlsplit(self.url)
93 path = p.path
94 if not path:
95 path = "/"
97 url.append(path)
99 query = p.query
100 if query:
101 url.append("?")
102 url.append(query)
104 return "".join(url)
106 @staticmethod
107 def _encode_params(data):
108 """Encode parameters in a piece of data.
110 Will successfully encode parameters when passed as a dict or a list of
111 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
112 if parameters are supplied as a dict.
113 """
115 if isinstance(data, (str, bytes)):
116 return data
117 elif hasattr(data, "read"):
118 return data
119 elif hasattr(data, "__iter__"):
120 result = []
121 for k, vs in to_key_val_list(data):
122 if isinstance(vs, basestring) or not hasattr(vs, "__iter__"):
123 vs = [vs]
124 for v in vs:
125 if v is not None:
126 result.append(
127 (
128 k.encode("utf-8") if isinstance(k, str) else k,
129 v.encode("utf-8") if isinstance(v, str) else v,
130 )
131 )
132 return urlencode(result, doseq=True)
133 else:
134 return data
136 @staticmethod
137 def _encode_files(files, data):
138 """Build the body for a multipart/form-data request.
140 Will successfully encode files when passed as a dict or a list of
141 tuples. Order is retained if data is a list of tuples but arbitrary
142 if parameters are supplied as a dict.
143 The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
144 or 4-tuples (filename, fileobj, contentype, custom_headers).
145 """
146 if not files:
147 raise ValueError("Files must be provided.")
148 elif isinstance(data, basestring):
149 raise ValueError("Data must not be a string.")
151 new_fields = []
152 fields = to_key_val_list(data or {})
153 files = to_key_val_list(files or {})
155 for field, val in fields:
156 if isinstance(val, basestring) or not hasattr(val, "__iter__"):
157 val = [val]
158 for v in val:
159 if v is not None:
160 # Don't call str() on bytestrings: in Py3 it all goes wrong.
161 if not isinstance(v, bytes):
162 v = str(v)
164 new_fields.append(
165 (
166 field.decode("utf-8")
167 if isinstance(field, bytes)
168 else field,
169 v.encode("utf-8") if isinstance(v, str) else v,
170 )
171 )
173 for k, v in files:
174 # support for explicit filename
175 ft = None
176 fh = None
177 if isinstance(v, (tuple, list)):
178 if len(v) == 2:
179 fn, fp = v
180 elif len(v) == 3:
181 fn, fp, ft = v
182 else:
183 fn, fp, ft, fh = v
184 else:
185 fn = guess_filename(v) or k
186 fp = v
188 if isinstance(fp, (str, bytes, bytearray)):
189 fdata = fp
190 elif hasattr(fp, "read"):
191 fdata = fp.read()
192 elif fp is None:
193 continue
194 else:
195 fdata = fp
197 rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)
198 rf.make_multipart(content_type=ft)
199 new_fields.append(rf)
201 body, content_type = encode_multipart_formdata(new_fields)
203 return body, content_type
206class RequestHooksMixin:
207 def register_hook(self, event, hook):
208 """Properly register a hook."""
210 if event not in self.hooks:
211 raise ValueError(f'Unsupported event specified, with event name "{event}"')
213 if isinstance(hook, Callable):
214 self.hooks[event].append(hook)
215 elif hasattr(hook, "__iter__"):
216 self.hooks[event].extend(h for h in hook if isinstance(h, Callable))
218 def deregister_hook(self, event, hook):
219 """Deregister a previously registered hook.
220 Returns True if the hook existed, False if not.
221 """
223 try:
224 self.hooks[event].remove(hook)
225 return True
226 except ValueError:
227 return False
230class Request(RequestHooksMixin):
231 """A user-created :class:`Request <Request>` object.
233 Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.
235 :param method: HTTP method to use.
236 :param url: URL to send.
237 :param headers: dictionary of headers to send.
238 :param files: dictionary of {filename: fileobject} files to multipart upload.
239 :param data: the body to attach to the request. If a dictionary or
240 list of tuples ``[(key, value)]`` is provided, form-encoding will
241 take place.
242 :param json: json for the body to attach to the request (if files or data is not specified).
243 :param params: URL parameters to append to the URL. If a dictionary or
244 list of tuples ``[(key, value)]`` is provided, form-encoding will
245 take place.
246 :param auth: Auth handler or (user, pass) tuple.
247 :param cookies: dictionary or CookieJar of cookies to attach to this request.
248 :param hooks: dictionary of callback hooks, for internal usage.
250 Usage::
252 >>> import requests
253 >>> req = requests.Request('GET', 'https://httpbin.org/get')
254 >>> req.prepare()
255 <PreparedRequest [GET]>
256 """
258 def __init__(
259 self,
260 method=None,
261 url=None,
262 headers=None,
263 files=None,
264 data=None,
265 params=None,
266 auth=None,
267 cookies=None,
268 hooks=None,
269 json=None,
270 ):
271 # Default empty dicts for dict params.
272 data = [] if data is None else data
273 files = [] if files is None else files
274 headers = {} if headers is None else headers
275 params = {} if params is None else params
276 hooks = {} if hooks is None else hooks
278 self.hooks = default_hooks()
279 for k, v in list(hooks.items()):
280 self.register_hook(event=k, hook=v)
282 self.method = method
283 self.url = url
284 self.headers = headers
285 self.files = files
286 self.data = data
287 self.json = json
288 self.params = params
289 self.auth = auth
290 self.cookies = cookies
292 def __repr__(self):
293 return f"<Request [{self.method}]>"
295 def prepare(self):
296 """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""
297 p = PreparedRequest()
298 p.prepare(
299 method=self.method,
300 url=self.url,
301 headers=self.headers,
302 files=self.files,
303 data=self.data,
304 json=self.json,
305 params=self.params,
306 auth=self.auth,
307 cookies=self.cookies,
308 hooks=self.hooks,
309 )
310 return p
313class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
314 """The fully mutable :class:`PreparedRequest <PreparedRequest>` object,
315 containing the exact bytes that will be sent to the server.
317 Instances are generated from a :class:`Request <Request>` object, and
318 should not be instantiated manually; doing so may produce undesirable
319 effects.
321 Usage::
323 >>> import requests
324 >>> req = requests.Request('GET', 'https://httpbin.org/get')
325 >>> r = req.prepare()
326 >>> r
327 <PreparedRequest [GET]>
329 >>> s = requests.Session()
330 >>> s.send(r)
331 <Response [200]>
332 """
334 def __init__(self):
335 #: HTTP verb to send to the server.
336 self.method = None
337 #: HTTP URL to send the request to.
338 self.url = None
339 #: dictionary of HTTP headers.
340 self.headers = None
341 # The `CookieJar` used to create the Cookie header will be stored here
342 # after prepare_cookies is called
343 self._cookies = None
344 #: request body to send to the server.
345 self.body = None
346 #: dictionary of callback hooks, for internal usage.
347 self.hooks = default_hooks()
348 #: integer denoting starting position of a readable file-like body.
349 self._body_position = None
351 def prepare(
352 self,
353 method=None,
354 url=None,
355 headers=None,
356 files=None,
357 data=None,
358 params=None,
359 auth=None,
360 cookies=None,
361 hooks=None,
362 json=None,
363 ):
364 """Prepares the entire request with the given parameters."""
366 self.prepare_method(method)
367 self.prepare_url(url, params)
368 self.prepare_headers(headers)
369 self.prepare_cookies(cookies)
370 self.prepare_body(data, files, json)
371 self.prepare_auth(auth, url)
373 # Note that prepare_auth must be last to enable authentication schemes
374 # such as OAuth to work on a fully prepared request.
376 # This MUST go after prepare_auth. Authenticators could add a hook
377 self.prepare_hooks(hooks)
379 def __repr__(self):
380 return f"<PreparedRequest [{self.method}]>"
382 def copy(self):
383 p = PreparedRequest()
384 p.method = self.method
385 p.url = self.url
386 p.headers = self.headers.copy() if self.headers is not None else None
387 p._cookies = _copy_cookie_jar(self._cookies)
388 p.body = self.body
389 p.hooks = self.hooks
390 p._body_position = self._body_position
391 return p
393 def prepare_method(self, method):
394 """Prepares the given HTTP method."""
395 self.method = method
396 if self.method is not None:
397 self.method = to_native_string(self.method.upper())
399 @staticmethod
400 def _get_idna_encoded_host(host):
401 import idna
403 try:
404 host = idna.encode(host, uts46=True).decode("utf-8")
405 except idna.IDNAError:
406 raise UnicodeError
407 return host
409 def prepare_url(self, url, params):
410 """Prepares the given HTTP URL."""
411 #: Accept objects that have string representations.
412 #: We're unable to blindly call unicode/str functions
413 #: as this will include the bytestring indicator (b'')
414 #: on python 3.x.
415 #: https://github.com/psf/requests/pull/2238
416 if isinstance(url, bytes):
417 url = url.decode("utf8")
418 else:
419 url = str(url)
421 # Remove leading whitespaces from url
422 url = url.lstrip()
424 # Don't do any URL preparation for non-HTTP schemes like `mailto`,
425 # `data` etc to work around exceptions from `url_parse`, which
426 # handles RFC 3986 only.
427 if ":" in url and not url.lower().startswith("http"):
428 self.url = url
429 return
431 # Support for unicode domain names and paths.
432 try:
433 scheme, auth, host, port, path, query, fragment = parse_url(url)
434 except LocationParseError as e:
435 raise InvalidURL(*e.args)
437 if not scheme:
438 raise MissingSchema(
439 f"Invalid URL {url!r}: No scheme supplied. "
440 f"Perhaps you meant https://{url}?"
441 )
443 if not host:
444 raise InvalidURL(f"Invalid URL {url!r}: No host supplied")
446 # In general, we want to try IDNA encoding the hostname if the string contains
447 # non-ASCII characters. This allows users to automatically get the correct IDNA
448 # behaviour. For strings containing only ASCII characters, we need to also verify
449 # it doesn't start with a wildcard (*), before allowing the unencoded hostname.
450 if not unicode_is_ascii(host):
451 try:
452 host = self._get_idna_encoded_host(host)
453 except UnicodeError:
454 raise InvalidURL("URL has an invalid label.")
455 elif host.startswith(("*", ".")):
456 raise InvalidURL("URL has an invalid label.")
458 # Carefully reconstruct the network location
459 netloc = auth or ""
460 if netloc:
461 netloc += "@"
462 netloc += host
463 if port:
464 netloc += f":{port}"
466 # Bare domains aren't valid URLs.
467 if not path:
468 path = "/"
470 if isinstance(params, (str, bytes)):
471 params = to_native_string(params)
473 enc_params = self._encode_params(params)
474 if enc_params:
475 if query:
476 query = f"{query}&{enc_params}"
477 else:
478 query = enc_params
480 url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))
481 self.url = url
483 def prepare_headers(self, headers):
484 """Prepares the given HTTP headers."""
486 self.headers = CaseInsensitiveDict()
487 if headers:
488 for header in headers.items():
489 # Raise exception on invalid header value.
490 check_header_validity(header)
491 name, value = header
492 self.headers[to_native_string(name)] = value
494 def prepare_body(self, data, files, json=None):
495 """Prepares the given HTTP body data."""
497 # Check if file, fo, generator, iterator.
498 # If not, run through normal process.
500 # Nottin' on you.
501 body = None
502 content_type = None
504 if not data and json is not None:
505 # urllib3 requires a bytes-like body. Python 2's json.dumps
506 # provides this natively, but Python 3 gives a Unicode string.
507 content_type = "application/json"
509 try:
510 body = complexjson.dumps(json, allow_nan=False)
511 except ValueError as ve:
512 raise InvalidJSONError(ve, request=self)
514 if not isinstance(body, bytes):
515 body = body.encode("utf-8")
517 is_stream = all(
518 [
519 hasattr(data, "__iter__"),
520 not isinstance(data, (basestring, list, tuple, Mapping)),
521 ]
522 )
524 if is_stream:
525 try:
526 length = super_len(data)
527 except (TypeError, AttributeError, UnsupportedOperation):
528 length = None
530 body = data
532 if getattr(body, "tell", None) is not None:
533 # Record the current file position before reading.
534 # This will allow us to rewind a file in the event
535 # of a redirect.
536 try:
537 self._body_position = body.tell()
538 except OSError:
539 # This differentiates from None, allowing us to catch
540 # a failed `tell()` later when trying to rewind the body
541 self._body_position = object()
543 if files:
544 raise NotImplementedError(
545 "Streamed bodies and files are mutually exclusive."
546 )
548 if length:
549 self.headers["Content-Length"] = builtin_str(length)
550 else:
551 self.headers["Transfer-Encoding"] = "chunked"
552 else:
553 # Multi-part file uploads.
554 if files:
555 (body, content_type) = self._encode_files(files, data)
556 else:
557 if data:
558 body = self._encode_params(data)
559 if isinstance(data, basestring) or hasattr(data, "read"):
560 content_type = None
561 else:
562 content_type = "application/x-www-form-urlencoded"
564 self.prepare_content_length(body)
566 # Add content-type if it wasn't explicitly provided.
567 if content_type and ("content-type" not in self.headers):
568 self.headers["Content-Type"] = content_type
570 self.body = body
572 def prepare_content_length(self, body):
573 """Prepare Content-Length header based on request method and body"""
574 if body is not None:
575 length = super_len(body)
576 if length:
577 # If length exists, set it. Otherwise, we fallback
578 # to Transfer-Encoding: chunked.
579 self.headers["Content-Length"] = builtin_str(length)
580 elif (
581 self.method not in ("GET", "HEAD")
582 and self.headers.get("Content-Length") is None
583 ):
584 # Set Content-Length to 0 for methods that can have a body
585 # but don't provide one. (i.e. not GET or HEAD)
586 self.headers["Content-Length"] = "0"
588 def prepare_auth(self, auth, url=""):
589 """Prepares the given HTTP auth data."""
591 # If no Auth is explicitly provided, extract it from the URL first.
592 if auth is None:
593 url_auth = get_auth_from_url(self.url)
594 auth = url_auth if any(url_auth) else None
596 if auth:
597 if isinstance(auth, tuple) and len(auth) == 2:
598 # special-case basic HTTP auth
599 auth = HTTPBasicAuth(*auth)
601 # Allow auth to make its changes.
602 r = auth(self)
604 # Update self to reflect the auth changes.
605 self.__dict__.update(r.__dict__)
607 # Recompute Content-Length
608 self.prepare_content_length(self.body)
610 def prepare_cookies(self, cookies):
611 """Prepares the given HTTP cookie data.
613 This function eventually generates a ``Cookie`` header from the
614 given cookies using cookielib. Due to cookielib's design, the header
615 will not be regenerated if it already exists, meaning this function
616 can only be called once for the life of the
617 :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls
618 to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
619 header is removed beforehand.
620 """
621 if isinstance(cookies, cookielib.CookieJar):
622 self._cookies = cookies
623 else:
624 self._cookies = cookiejar_from_dict(cookies)
626 cookie_header = get_cookie_header(self._cookies, self)
627 if cookie_header is not None:
628 self.headers["Cookie"] = cookie_header
630 def prepare_hooks(self, hooks):
631 """Prepares the given hooks."""
632 # hooks can be passed as None to the prepare method and to this
633 # method. To prevent iterating over None, simply use an empty list
634 # if hooks is False-y
635 hooks = hooks or []
636 for event in hooks:
637 self.register_hook(event, hooks[event])
640class Response:
641 """The :class:`Response <Response>` object, which contains a
642 server's response to an HTTP request.
643 """
645 __attrs__ = [
646 "_content",
647 "status_code",
648 "headers",
649 "url",
650 "history",
651 "encoding",
652 "reason",
653 "cookies",
654 "elapsed",
655 "request",
656 ]
658 def __init__(self):
659 self._content = False
660 self._content_consumed = False
661 self._next = None
663 #: Integer Code of responded HTTP Status, e.g. 404 or 200.
664 self.status_code = None
666 #: Case-insensitive Dictionary of Response Headers.
667 #: For example, ``headers['content-encoding']`` will return the
668 #: value of a ``'Content-Encoding'`` response header.
669 self.headers = CaseInsensitiveDict()
671 #: File-like object representation of response (for advanced usage).
672 #: Use of ``raw`` requires that ``stream=True`` be set on the request.
673 #: This requirement does not apply for use internally to Requests.
674 self.raw = None
676 #: Final URL location of Response.
677 self.url = None
679 #: Encoding to decode with when accessing r.text.
680 self.encoding = None
682 #: A list of :class:`Response <Response>` objects from
683 #: the history of the Request. Any redirect responses will end
684 #: up here. The list is sorted from the oldest to the most recent request.
685 self.history = []
687 #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
688 self.reason = None
690 #: A CookieJar of Cookies the server sent back.
691 self.cookies = cookiejar_from_dict({})
693 #: The amount of time elapsed between sending the request
694 #: and the arrival of the response (as a timedelta).
695 #: This property specifically measures the time taken between sending
696 #: the first byte of the request and finishing parsing the headers. It
697 #: is therefore unaffected by consuming the response content or the
698 #: value of the ``stream`` keyword argument.
699 self.elapsed = datetime.timedelta(0)
701 #: The :class:`PreparedRequest <PreparedRequest>` object to which this
702 #: is a response.
703 self.request = None
705 def __enter__(self):
706 return self
708 def __exit__(self, *args):
709 self.close()
711 def __getstate__(self):
712 # Consume everything; accessing the content attribute makes
713 # sure the content has been fully read.
714 if not self._content_consumed:
715 self.content
717 return {attr: getattr(self, attr, None) for attr in self.__attrs__}
719 def __setstate__(self, state):
720 for name, value in state.items():
721 setattr(self, name, value)
723 # pickled objects do not have .raw
724 setattr(self, "_content_consumed", True)
725 setattr(self, "raw", None)
727 def __repr__(self):
728 return f"<Response [{self.status_code}]>"
730 def __bool__(self):
731 """Returns True if :attr:`status_code` is less than 400.
733 This attribute checks if the status code of the response is between
734 400 and 600 to see if there was a client error or a server error. If
735 the status code, is between 200 and 400, this will return True. This
736 is **not** a check to see if the response code is ``200 OK``.
737 """
738 return self.ok
740 def __nonzero__(self):
741 """Returns True if :attr:`status_code` is less than 400.
743 This attribute checks if the status code of the response is between
744 400 and 600 to see if there was a client error or a server error. If
745 the status code, is between 200 and 400, this will return True. This
746 is **not** a check to see if the response code is ``200 OK``.
747 """
748 return self.ok
750 def __iter__(self):
751 """Allows you to use a response as an iterator."""
752 return self.iter_content(128)
754 @property
755 def ok(self):
756 """Returns True if :attr:`status_code` is less than 400, False if not.
758 This attribute checks if the status code of the response is between
759 400 and 600 to see if there was a client error or a server error. If
760 the status code is between 200 and 400, this will return True. This
761 is **not** a check to see if the response code is ``200 OK``.
762 """
763 try:
764 self.raise_for_status()
765 except HTTPError:
766 return False
767 return True
769 @property
770 def is_redirect(self):
771 """True if this Response is a well-formed HTTP redirect that could have
772 been processed automatically (by :meth:`Session.resolve_redirects`).
773 """
774 return "location" in self.headers and self.status_code in REDIRECT_STATI
776 @property
777 def is_permanent_redirect(self):
778 """True if this Response one of the permanent versions of redirect."""
779 return "location" in self.headers and self.status_code in (
780 codes.moved_permanently,
781 codes.permanent_redirect,
782 )
784 @property
785 def next(self):
786 """Returns a PreparedRequest for the next request in a redirect chain, if there is one."""
787 return self._next
789 @property
790 def apparent_encoding(self):
791 """The apparent encoding, provided by the charset_normalizer or chardet libraries."""
792 if chardet is not None:
793 return chardet.detect(self.content)["encoding"]
794 else:
795 # If no character detection library is available, we'll fall back
796 # to a standard Python utf-8 str.
797 return "utf-8"
799 def iter_content(self, chunk_size=1, decode_unicode=False):
800 """Iterates over the response data. When stream=True is set on the
801 request, this avoids reading the content at once into memory for
802 large responses. The chunk size is the number of bytes it should
803 read into memory. This is not necessarily the length of each item
804 returned as decoding can take place.
806 chunk_size must be of type int or None. A value of None will
807 function differently depending on the value of `stream`.
808 stream=True will read data as it arrives in whatever size the
809 chunks are received. If stream=False, data is returned as
810 a single chunk.
812 If decode_unicode is True, content will be decoded using the best
813 available encoding based on the response.
814 """
816 def generate():
817 # Special case for urllib3.
818 if hasattr(self.raw, "stream"):
819 try:
820 yield from self.raw.stream(chunk_size, decode_content=True)
821 except ProtocolError as e:
822 raise ChunkedEncodingError(e)
823 except DecodeError as e:
824 raise ContentDecodingError(e)
825 except ReadTimeoutError as e:
826 raise ConnectionError(e)
827 except SSLError as e:
828 raise RequestsSSLError(e)
829 else:
830 # Standard file-like object.
831 while True:
832 chunk = self.raw.read(chunk_size)
833 if not chunk:
834 break
835 yield chunk
837 self._content_consumed = True
839 if self._content_consumed and isinstance(self._content, bool):
840 raise StreamConsumedError()
841 elif chunk_size is not None and not isinstance(chunk_size, int):
842 raise TypeError(
843 f"chunk_size must be an int, it is instead a {type(chunk_size)}."
844 )
845 # simulate reading small chunks of the content
846 reused_chunks = iter_slices(self._content, chunk_size)
848 stream_chunks = generate()
850 chunks = reused_chunks if self._content_consumed else stream_chunks
852 if decode_unicode:
853 chunks = stream_decode_response_unicode(chunks, self)
855 return chunks
857 def iter_lines(
858 self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None
859 ):
860 """Iterates over the response data, one line at a time. When
861 stream=True is set on the request, this avoids reading the
862 content at once into memory for large responses.
864 .. note:: This method is not reentrant safe.
865 """
867 pending = None
869 for chunk in self.iter_content(
870 chunk_size=chunk_size, decode_unicode=decode_unicode
871 ):
872 if pending is not None:
873 chunk = pending + chunk
875 if delimiter:
876 lines = chunk.split(delimiter)
877 else:
878 lines = chunk.splitlines()
880 if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
881 pending = lines.pop()
882 else:
883 pending = None
885 yield from lines
887 if pending is not None:
888 yield pending
890 @property
891 def content(self):
892 """Content of the response, in bytes."""
894 if self._content is False:
895 # Read the contents.
896 if self._content_consumed:
897 raise RuntimeError("The content for this response was already consumed")
899 if self.status_code == 0 or self.raw is None:
900 self._content = None
901 else:
902 self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b""
904 self._content_consumed = True
905 # don't need to release the connection; that's been handled by urllib3
906 # since we exhausted the data.
907 return self._content
909 @property
910 def text(self):
911 """Content of the response, in unicode.
913 If Response.encoding is None, encoding will be guessed using
914 ``charset_normalizer`` or ``chardet``.
916 The encoding of the response content is determined based solely on HTTP
917 headers, following RFC 2616 to the letter. If you can take advantage of
918 non-HTTP knowledge to make a better guess at the encoding, you should
919 set ``r.encoding`` appropriately before accessing this property.
920 """
922 # Try charset from content-type
923 content = None
924 encoding = self.encoding
926 if not self.content:
927 return ""
929 # Fallback to auto-detected encoding.
930 if self.encoding is None:
931 encoding = self.apparent_encoding
933 # Decode unicode from given encoding.
934 try:
935 content = str(self.content, encoding, errors="replace")
936 except (LookupError, TypeError):
937 # A LookupError is raised if the encoding was not found which could
938 # indicate a misspelling or similar mistake.
939 #
940 # A TypeError can be raised if encoding is None
941 #
942 # So we try blindly encoding.
943 content = str(self.content, errors="replace")
945 return content
947 def json(self, **kwargs):
948 r"""Returns the json-encoded content of a response, if any.
950 :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
951 :raises requests.exceptions.JSONDecodeError: If the response body does not
952 contain valid json.
953 """
955 if not self.encoding and self.content and len(self.content) > 3:
956 # No encoding set. JSON RFC 4627 section 3 states we should expect
957 # UTF-8, -16 or -32. Detect which one to use; If the detection or
958 # decoding fails, fall back to `self.text` (using charset_normalizer to make
959 # a best guess).
960 encoding = guess_json_utf(self.content)
961 if encoding is not None:
962 try:
963 return complexjson.loads(self.content.decode(encoding), **kwargs)
964 except UnicodeDecodeError:
965 # Wrong UTF codec detected; usually because it's not UTF-8
966 # but some other 8-bit codec. This is an RFC violation,
967 # and the server didn't bother to tell us what codec *was*
968 # used.
969 pass
970 except JSONDecodeError as e:
971 raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
973 try:
974 return complexjson.loads(self.text, **kwargs)
975 except JSONDecodeError as e:
976 # Catch JSON-related errors and raise as requests.JSONDecodeError
977 # This aliases json.JSONDecodeError and simplejson.JSONDecodeError
978 raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
980 @property
981 def links(self):
982 """Returns the parsed header links of the response, if any."""
984 header = self.headers.get("link")
986 resolved_links = {}
988 if header:
989 links = parse_header_links(header)
991 for link in links:
992 key = link.get("rel") or link.get("url")
993 resolved_links[key] = link
995 return resolved_links
997 def raise_for_status(self):
998 """Raises :class:`HTTPError`, if one occurred."""
1000 http_error_msg = ""
1001 if isinstance(self.reason, bytes):
1002 # We attempt to decode utf-8 first because some servers
1003 # choose to localize their reason strings. If the string
1004 # isn't utf-8, we fall back to iso-8859-1 for all other
1005 # encodings. (See PR #3538)
1006 try:
1007 reason = self.reason.decode("utf-8")
1008 except UnicodeDecodeError:
1009 reason = self.reason.decode("iso-8859-1")
1010 else:
1011 reason = self.reason
1013 if 400 <= self.status_code < 500:
1014 http_error_msg = (
1015 f"{self.status_code} Client Error: {reason} for url: {self.url}"
1016 )
1018 elif 500 <= self.status_code < 600:
1019 http_error_msg = (
1020 f"{self.status_code} Server Error: {reason} for url: {self.url}"
1021 )
1023 if http_error_msg:
1024 raise HTTPError(http_error_msg, response=self)
1026 def close(self):
1027 """Releases the connection back to the pool. Once this method has been
1028 called the underlying ``raw`` object must not be accessed again.
1030 *Note: Should not normally need to be called explicitly.*
1031 """
1032 if not self._content_consumed:
1033 self.raw.close()
1035 release_conn = getattr(self.raw, "release_conn", None)
1036 if release_conn is not None:
1037 release_conn()