Refs -- Optimized HttpResponseBase.charset a bit.
This avoids scanning the Content-Type if it's empty, allowing the
Content-Type header itself to have a charset assigned without using
the re module.
@@ -152,10 +152,14 @@ class HttpResponseBase:
def charset(self):
if self._charset is not None:
return self._charset
- content_type = self.get("Content-Type", "")
- matched = _charset_from_content_type_re.search(content_type)
- if matched:
- # Extract the charset and strip its double quotes
+ # The Content-Type header may not yet be set, because the charset is
+ # being inserted *into* it.
+ if content_type := self.headers.get("Content-Type"):
+ if matched := _charset_from_content_type_re.search(content_type):
+ # Extract the charset and strip its double quotes.
+ # Note that having parsed it from the Content-Type, we don't
+ # store it back into the _charset for later intentionally, to
+ # allow for the Content-Type to be switched again later.
return matched["charset"].replace('"', "")
return settings.DEFAULT_CHARSET
