Repository navigation
Fall back to utf-8 when charset autodetection needs unread content - #3879
qianeric-backup wants to merge 1 commit into
Conversation
Response.encoding rejects a header charset that is not a Python codec, then tries to replace it with default_encoding. With a callable default_encoding and unread content neither the string branch nor the callable branch runs, so the rejected charset survives `or "utf-8"` (it is truthy) and is cached, making every later text access raise LookupError. The callable form is for autodetection, which needs the body; before that there is nothing to detect from. Fall back to utf-8, as the same line already does when no charset was given at all. Discussed in encode#3878.
ege-arhan
left a comment
There was a problem hiding this comment.
encoding memoizes the fallback, so the autodetection callable never runs once the content is available.
httpx/_models.py:672-676: when default_encoding is a callable and _content is missing, the new branch sets encoding = None and line 676 then stores "utf-8" in self._encoding. text and iter_text both go through this property, so by the time the body is read the value is already cached and default_encoding(self._content) is never called.
Repro on 598711f:
import httpx
body = "Euro Currency: \u20ac abcdef".encode("cp1252")
r = httpx.Response(
200,
headers={"Content-Type": "text/plain; charset=invalid-codec"},
stream=httpx.ByteStream(body),
default_encoding=lambda content: "cp1252",
)
print(r.encoding) # utf-8, cached by the new branch
r.read()
print(r.encoding) # still utf-8
print(r.text == body.decode("cp1252")) # False, the euro sign decodes to U+FFFDOn main the same code raises LookupError: unknown encoding: invalid-codec from TextDecoder, so the crash itself is fixed. But the detected encoding is thrown away, and every response that is streamed before .text is accessed decodes with utf-8 and replacement characters instead. The new tests only use a utf-8 autodetect function, so this path is not covered.
Returning the placeholder without caching keeps the fix and lets the property re-evaluate:
else:
# The content has not been read yet, so the callable cannot run.
# Do not memoize the placeholder; the next access can autodetect.
return "utf-8"With that change the repro prints utf-8, then cp1252, and r.text matches body.decode("cp1252").
python -m pytest tests/models/test_responses.py on this branch: 4 failed, 105 passed. The same 4 fail on main here (chardet picks iso8859-15 for the latin-1 fixtures), so they are unrelated to the PR.
Discussed first, as the contributing guide asks: #3878.
Response.encodingcaches a charset Python has no codec for whendefault_encodingis a callable and the content has not been read yet:>>> response.encoding 'x-user-defined' >>> b"".join(response.iter_bytes()).decode(response.encoding) LookupError: unknown encoding: x-user-defined_is_known_encoding()correctly rejects the header'sx-user-defined, and the property then picks a replacement:A string
default_encodingreplaces the rejected charset. A callable one with unread content takes neither branch, soencodingis still the rejected value, andor "utf-8"does not catch it because a non-empty string is truthy. The same response viaclient.get()decodes fine, so whether a response is readable depends on how it was fetched.The callable form exists for autodetection, which by definition needs the body; before that point there is nothing to detect from, and the line above already falls back to
utf-8when there is no charset at all.Change
elif hasattr(self, "_content"): encoding = self.default_encoding(self._content) + else: + # The callable `default_encoding` requires the response content, + # which has not been read yet. Fall back to utf-8 rather than + # passing an unusable charset through. + encoding = NoneTests
Three cases in
tests/models/test_responses.py: the streaming call above, the same response read eagerly (unchanged behaviour), and a known charset with unread content (still honoured).master1417 passed, 1 skippedmaster+ the tests,_models.pyuntouched2 failed, 1418 passed, 1 skipped— bothLookupError: unknown encoding: x-user-defined1420 passed, 1 skippedcomm -3over the failure lists is empty againstmasterand shows exactly the two new tests against the red tree.18 legal responses compared byte for byte (known and unknown charsets, string and callable
default_encoding, eager and streaming reads, absent charset) produce identical output before and after.ruff format --diff,ruff check,mypy,scripts/sync-version, andcoverage --fail-under=100(100% after the change) are clean.Noting the guide's point that effort has moved to hip: this is small and contained, but I understand if it is not worth triaging now.