requests icon indicating copy to clipboard operation
requests copied to clipboard

get_encoding_from_headers treats any content type containing 'text' as text/* (ISO-8859-1)

Open 10k11 opened this issue 3 weeks ago • 1 comments

Summary

requests.utils.get_encoding_from_headers uses substring checks on the media type, so non-text/* types that merely contain the letters "text" are treated as text and get ISO-8859-1.

In src/requests/utils.py:

if "text" in content_type:
    return "ISO-8859-1"

Repro

from requests.utils import get_encoding_from_headers
from requests.structures import CaseInsensitiveDict as C

get_encoding_from_headers(C({"content-type": "application/vnd.context+xml"}))  # 'ISO-8859-1'
get_encoding_from_headers(C({"content-type": "application/x-context"}))        # 'ISO-8859-1'

Neither is a text/* type, so Response.encoding should be None (letting content-based detection run), not Latin-1. The same substring pattern is used for "application/json" in content_type, which would also match e.g. application/jsonx.

Suggested fix

Compare against the parsed media type, e.g. content_type.startswith("text/") and content_type == "application/json". Happy to open a PR with tests.

Checked on current main; I found no existing issue covering this.

10k11 avatar Nov 08 '26 08:11 10k11

Hi maintainers,

I would like to contribute to this issue as an independent contributor.

I have intermediate Python knowledge and would like to fix the content-type detection logic in get_encoding_from_headers and add regression tests for the affected cases.

I have reviewed the issue and would be happy to work on this improvement.

Could you please confirm whether I can proceed?

Thank you!

suyashgitt avatar Nov 13 '26 18:11 suyashgitt