Refs #33546 -- 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.
This commit is contained in:
Keryn Knight 2022-02-09 19:42:44 +00:00 committed by Mariusz Felisiak
parent 51f896fe25
commit 4b2f6ace57
1 changed files with 9 additions and 5 deletions

View File

@ -152,11 +152,15 @@ 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
return matched["charset"].replace('"', "")
# 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
@charset.setter