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