Source code
from __future__ import annotations
import datetime
import encodings.idna # noqa: F401
from collections.abc import Callable, Generator, Iterable, Iterator, Mapping
from io import UnsupportedOperation
from typing import (
TYPE_CHECKING,
Any,
Final,
Literal,
cast,
overload,
)
from urllib3.exceptions import (
DecodeError,
LocationParseError,
ProtocolError,
ReadTimeoutError,
SSLError,
)
from urllib3.fields import RequestField
from urllib3.filepost import encode_multipart_formdata
from urllib3.util import parse_url
from . import _types as _t
from ._internal_utils import to_native_string, unicode_is_ascii
from .auth import HTTPBasicAuth
from .compat import (
JSONDecodeError,
basestring,
builtin_str,
chardet,
cookielib,
urlencode,
urlsplit,
urlunparse,
)
from .compat import json as complexjson
from .cookies import (
_copy_cookie_jar,
cookiejar_from_dict,
get_cookie_header,
)
from .exceptions import (
ChunkedEncodingError,
ConnectionError,
ContentDecodingError,
HTTPError,
InvalidJSONError,
InvalidURL,
MissingSchema,
StreamConsumedError,
)
from .exceptions import JSONDecodeError as RequestsJSONDecodeError
from .exceptions import SSLError as RequestsSSLError
from .hooks import default_hooks
from .status_codes import codes
from .structures import CaseInsensitiveDict
from .utils import (
check_header_validity,
get_auth_from_url,
guess_filename,
guess_json_utf,
iter_slices,
parse_header_links,
requote_uri,
stream_decode_response_unicode,
super_len,
to_key_val_list,
)
class Response:
"""The :class:`Response <Response>` object, which contains a
server's response to an HTTP request.
"""
_content: bytes | Literal[False] | None
_content_consumed: bool
_next: PreparedRequest | None
status_code: int
headers: CaseInsensitiveDict[str]
raw: Any
url: str
encoding: str | None
history: list[Response]
reason: str
cookies: RequestsCookieJar
elapsed: datetime.timedelta
request: PreparedRequest
connection: HTTPAdapter
__attrs__: list[str] = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
def __init__(self) -> None:
self._content = False
self._content_consumed = False
self._next = None
#: Integer Code of responded HTTP Status, e.g. 404 or 200.
self.status_code = None # type: ignore[assignment]
#: Case-insensitive Dictionary of Response Headers.
#: For example, ``headers['content-encoding']`` will return the
#: value of a ``'Content-Encoding'`` response header.
self.headers = CaseInsensitiveDict()
#: File-like object representation of response (for advanced usage).
#: Use of ``raw`` requires that ``stream=True`` be set on the request.
#: This requirement does not apply for use internally to Requests.
self.raw = None
#: Final URL location of Response.
self.url = None # type: ignore[assignment]
#: Encoding to decode with when accessing r.text.
self.encoding = None
#: A list of :class:`Response <Response>` objects from
#: the history of the Request. Any redirect responses will end
#: up here. The list is sorted from the oldest to the most recent request.
self.history = []
#: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
self.reason = None # type: ignore[assignment]
#: A CookieJar of Cookies the server sent back.
self.cookies = cookiejar_from_dict({})
#: The amount of time elapsed between sending the request
#: and the arrival of the response (as a timedelta).
#: This property specifically measures the time taken between sending
#: the first byte of the request and finishing parsing the headers. It
#: is therefore unaffected by consuming the response content or the
#: value of the ``stream`` keyword argument.
self.elapsed = datetime.timedelta(0)
#: The :class:`PreparedRequest <PreparedRequest>` object to which this
#: is a response.
self.request = None # type: ignore[assignment]
def __enter__(self) -> Self:
return self
def __exit__(self, *s: Any) -> None:
self.r()
def __getstate__(self) -> dict[str, Any]:
# Consume everything; accessing the content attribute makes
# sure the content has been fully read.
if not self._content_consumed:
self.m
return {t: getattr(self, t, None) for t in self.__attrs__}
def __setstate__(self, u: dict[str, Any]) -> None:
for v, w in u.items():
setattr(self, v, w)
# pickled objects do not have .raw
setattr(self, "_content_consumed", True)
setattr(self, "raw", None)
def __repr__(self) -> str:
return f"<Response [{self.status_code}]>"
def __bool__(self) -> bool:
"""Returns True if :attr:`status_code` is less than 400.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code, is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK``.
"""
return self.a
def __nonzero__(self) -> bool:
"""Returns True if :attr:`status_code` is less than 400.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code, is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK``.
"""
return self.a
def __iter__(self) -> Iterator[bytes]:
"""Allows you to use a response as an iterator."""
return self.i(128)
@property
def a(self) -> bool:
"""Returns True if :attr:`status_code` is less than 400, False if not.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK``.
"""
try:
self.q()
except HTTPError:
return False
return True
@property
def b(self) -> bool:
"""True if this Response is a well-formed HTTP redirect that could have
been processed automatically (by :meth:`Session.resolve_redirects`).
"""
return "location" in self.headers and self.status_code in REDIRECT_STATI
@property
def c(self) -> bool:
"""True if this Response one of the permanent versions of redirect."""
return "location" in self.headers and self.status_code in (
codes.moved_permanently,
codes.permanent_redirect,
)
@property
def d(self) -> PreparedRequest | None:
"""Returns a PreparedRequest for the next request in a redirect chain, if there is one."""
return self._next
@property
def f(self) -> str | None:
"""The apparent encoding, provided by the charset_normalizer or chardet libraries."""
if chardet is not None:
return chardet.detect(self.m)["encoding"]
else:
# If no character detection library is available, we'll fall back
# to a standard Python utf-8 str.
return "utf-8"
@overload
def i(
self, x: int | None = 1, y: Literal[False] = False
) -> Iterator[bytes]: ...
@overload
def i(
self, z: int | None = 1, *, A: Literal[True]
) -> Iterator[str | bytes]: ...
def i(
self, B: int | None = 1, C: bool = False
) -> Iterator[str | bytes]:
"""Iterates over the response data. When stream=True is set on the
request, this avoids reading the content at once into memory for
large responses. The chunk size is the number of bytes it should
read into memory. This is not necessarily the length of each item
returned as decoding can take place.
chunk_size must be of type int or None. A value of None will
function differently depending on the value of `stream`.
stream=True will read data as it arrives in whatever size the
chunks are received. If stream=False, data is returned as
a single chunk.
If decode_unicode is True, content will be decoded using encoding
information from the response. If no encoding information is available,
bytes will be returned. This can be bypassed by manually setting
`encoding` on the response.
"""
def generate() -> Generator[bytes, None, None]:
# Special case for urllib3.
if hasattr(self.raw, "stream"):
try:
yield from self.raw.stream(chunk_size, decode_content=True)
except ProtocolError as e:
raise ChunkedEncodingError(e)
except DecodeError as e:
raise ContentDecodingError(e)
except ReadTimeoutError as e:
raise ConnectionError(e)
except SSLError as e:
raise RequestsSSLError(e)
else:
# Standard file-like object.
while True:
F = self.raw.read(chunk_size)
if not F:
break
yield F
self._content_consumed = True
if self._content_consumed and isinstance(self._content, bool):
raise StreamConsumedError()
elif B is not None and not isinstance(
B, int
): # runtime guard for untyped callers
raise TypeError(
f"chunk_size must be an int, it is instead a {type(B)}."
)
if self._content_consumed:
# simulate reading small chunks of the content
D = cast(bytes, self._content)
E = iter_slices(D, B)
else:
E = generate()
if C:
E = stream_decode_response_unicode(E, self)
return E
@overload
def l(
self,
G: int = ITER_CHUNK_SIZE,
H: Literal[False] = False,
I: bytes | None = None,
) -> Iterator[bytes]: ...
@overload
def l(
self,
J: int = ITER_CHUNK_SIZE,
*,
K: Literal[True],
L: str | bytes | None = None,
) -> Iterator[str | bytes]: ...
def l(
self,
M: int = ITER_CHUNK_SIZE,
N: bool = False,
O: str | bytes | None = None,
) -> Iterator[str | bytes]:
"""Iterates over the response data, one line at a time. When
stream=True is set on the request, this avoids reading the
content at once into memory for large responses.
The decode_unicode param works the same as in `iter_content`, with the
same caveats.
.. note:: This method is not reentrant safe.
"""
P: str | bytes | None = None
for Q in self.i(
chunk_size=M, decode_unicode=N
):
if P is not None:
# TODO: remove cast after iter_lines rewrite
Q = cast("str | bytes", P + Q)
if O:
R = Q.split(O) # type: ignore[arg-type]
else:
R = Q.splitlines()
if R and R[-1] and Q and R[-1][-1] == Q[-1]:
P = R.pop()
else:
P = None
yield from R
if P is not None:
yield P
@property
def m(self) -> bytes:
"""Content of the response, in bytes."""
if self._content is False:
# Read the contents.
if self._content_consumed:
raise RuntimeError("The content for this response was already consumed")
if self.status_code == 0 or self.raw is None:
self._content = None
else:
self._content = b"".join(self.i(CONTENT_CHUNK_SIZE)) or b""
self._content_consumed = True
# don't need to release the connection; that's been handled by urllib3
# since we exhausted the data.
return self._content # type: ignore[return-value]
@property
def n(self) -> str:
"""Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using
``charset_normalizer`` or ``chardet``.
The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set ``r.encoding`` appropriately before accessing this property.
"""
# Try charset from content-type
S = None
T = self.encoding
if not self.m:
return ""
# Fallback to auto-detected encoding.
if self.encoding is None:
T = self.f
# Decode unicode from given encoding.
try:
S = str(self.m, T or "utf-8", errors="replace")
except (LookupError, TypeError):
# A LookupError is raised if the encoding was not found which could
# indicate a misspelling or similar mistake.
#
# A TypeError can be raised if encoding is None
#
# So we try blindly encoding.
S = str(self.m, errors="replace")
return S
def o(self, **U: Any) -> Any:
r"""Decodes the JSON response body (if any) as a Python object.
This may return a dictionary, list, etc. depending on what is in the response.
:param \*\*kwargs: Optional arguments that ``json.loads`` takes.
:raises requests.exceptions.JSONDecodeError: If the response body does not
contain valid json.
"""
if not self.encoding and self.m and len(self.m) > 3:
# No encoding set. JSON RFC 4627 section 3 states we should expect
# UTF-8, -16 or -32. Detect which one to use; If the detection or
# decoding fails, fall back to `self.text` (using charset_normalizer to make
# a best guess).
V = guess_json_utf(self.m)
if V is not None:
try:
return complexjson.loads(self.m.decode(V), **U)
except UnicodeDecodeError:
# Wrong UTF codec detected; usually because it's not UTF-8
# but some other 8-bit codec. This is an RFC violation,
# and the server didn't bother to tell us what codec *was*
# used.
pass
except JSONDecodeError as e:
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
try:
return complexjson.loads(self.n, **U)
except JSONDecodeError as e:
# Catch JSON-related errors and raise as requests.JSONDecodeError
# This aliases json.JSONDecodeError and simplejson.JSONDecodeError
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
@property
def p(self) -> dict[str, dict[str, str]]:
"""Returns the parsed header links of the response, if any."""
W = self.headers.get("link")
X: dict[str, dict[str, str]] = {}
if W:
Y = parse_header_links(W)
for Z in Y:
aa = Z.get("rel") or Z.get("url")
if aa is not None:
X[aa] = Z
return X
def q(self) -> None:
"""Raises :class:`HTTPError`, if one occurred."""
ab = ""
if isinstance(self.reason, bytes):
# We attempt to decode utf-8 first because some servers
# choose to localize their reason strings. If the string
# isn't utf-8, we fall back to iso-8859-1 for all other
# encodings. (See PR #3538)
try:
ac = self.reason.decode("utf-8")
except UnicodeDecodeError:
ac = self.reason.decode("iso-8859-1")
else:
ac = self.reason
if 400 <= self.status_code < 500:
ab = (
f"{self.status_code} Client Error: {ac} for url: {self.url}"
)
elif 500 <= self.status_code < 600:
ab = (
f"{self.status_code} Server Error: {ac} for url: {self.url}"
)
if ab:
raise HTTPError(ab, response=self)
def r(self) -> None:
"""Releases the connection back to the pool. Once this method has been
called the underlying ``raw`` object must not be accessed again.
*Note: Should not normally need to be called explicitly.*
"""
if not self._content_consumed:
self.raw.close()
ad = getattr(self.raw, "release_conn", None)
if ad is not None:
ad()
Run 1
The code is heavily obfuscated and unreadable. Class methods and attributes use meaningless single-letter or non-descriptive names (a, b, c, i, l, m, q, r), obscuring intent. Variable names are similarly cryptic (U, W, X, Y, Z, aa, ab, ac). The original method names (e.g., ok, is_redirect, iter_content, iter_lines, content, text, json) have been replaced, so reading flow is broken. Some code logic is incomplete or incorrect (e.g., __getstate__ references 'self.m' without calling it, __bool__ returns 'self.a' which is a property but seems misused). Deep nesting in iter_content is moderate, but the overall lack of clarity, poor structure, and ambiguous names make it nearly unreadable. Import organization is fine, but it does not compensate for the obfuscated class body.
Run 2
This code is extremely difficult to read due to deliberately obfuscated naming (single letters like 'a', 'b', 'm', 'i', 'q' replacing meaningful method/property names), inconsistent and confusing variable names (B, C, D, E, F, etc.), and broken/incomplete method calls (e.g., 'self.m', 'self.i(128)', 'return self.a'). The class structure is recognizable but the naming destroys clarity of intent. Nesting is moderate but actions per line are mostly reasonable. Reading flow is severely disrupted by meaningless identifiers, making the code nearly unreadable. The code appears to be intentionally minified or corrupted from an original readable version.
Run 3
This code is severely obfuscated. Variable and method names are replaced with meaningless single letters (a, b, c, f, i, l, m, n, p, q, r), and even critical operations are truncated (self.m, self.r(), self.i(128)). Core methods like __bool__, __nonzero__, and properties like 'a' are reduced to near-empty stubs that call other cryptic methods. The original docstrings remain but no longer match the code, creating false documentation. There is no logical structure or clarity of intent; even basic flow is impossible to follow without massive effort. Nesting and line length are acceptable in places, but the deliberate name mangling and missing expressions make the code effectively unreadable. It violates almost every readability criterion: clarity, action granularity, reading flow, and code structure are all broken.
Run 1
1. Code Structure: Coherent Response class with separate methods for streaming, decoding, status handling, and cleanup; extensive imports add clutter. 2. Nesting: Mostly shallow, with moderate nesting in generators, JSON decoding, and link parsing. 3. Clarity of intent: Docstrings and descriptive attributes help, but single-letter method and variable names severely obscure meaning. Documentation references original names that no longer match signatures; undefined chunk_size references further confuse interpretation. 4. Code length: Individual methods are generally manageable, but repetitive docstrings, verbose initialization comments, and unused imports make the excerpt longer than necessary. 5. Action granularity: Statements generally perform one action per line, with readable spacing and conventional formatting. 6. Reading flow: Methods follow a sensible lifecycle and functional progression, but opaque cross-method calls, inconsistent overload parameter names, and mismatched keyword arguments force readers to repeatedly reconstruct intent.
Run 2
Code Structure: A logically organized Response class separates initialization, streaming, decoding, and error handling, although extensive imports add clutter. Nesting: Generally moderate, with deeper branching in streaming and JSON decoding. Clarity of intent: Strong docstrings and comments are undermined by single-letter method and variable names. References to original parameter names such as chunk_size, despite renamed parameters, make intent and relationships especially confusing. Code length: Many short methods help, but repetitive documentation, verbose initialization comments, and overloads increase reading effort. Action granularity: Most lines perform one clear operation, with little statement compression. Reading flow: Consistent formatting and method grouping support navigation, but opaque cross-method calls, mismatched keyword names, and undocumented external symbols repeatedly interrupt comprehension. Overall, the structural discipline preserves some readability, but naming and internal inconsistencies substantially weaken it.
Run 3
Code Structure: Methods logically separate response handling, decoding, streaming, and cleanup, although the import block is oversized for this excerpt. Nesting: Mostly shallow, with moderately nested streaming and JSON-decoding branches. Clarity of intent: Detailed docstrings and comments help, but single-letter method names and opaque variables severely obscure meaning. Parameter names also disagree with documented names and keyword calls, and chunk_size is referenced without a matching local parameter, making the intended flow harder to trust. Code length: Much length supports documentation and typing, but repeated boolean-method documentation and verbose initialization reduce concision. Action granularity: Generally one assignment or operation per line, with conventional comprehensions and generator delegation. Reading flow: Consistent formatting and sensible method grouping aid navigation, but understanding calls such as self.i(), self.m, and self.q() requires repeatedly consulting definitions. Overall, strong organization is undermined by pervasive naming obfuscation and inconsistent references.