summaryrefslogtreecommitdiff
path: root/django/http
diff options
context:
space:
mode:
authorKeryn Knight <keryn@kerynknight.com>2022-02-09 19:42:44 +0000
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2022-03-02 20:23:39 +0100
commit4b2f6ace5789768a5734b017b70b3dec31bb000c (patch)
tree84e0debb308440a083fd9950d93ac928dd22b398 /django/http
parent51f896fe25d0593abad2b3c55fd510c46ef57f05 (diff)
downloaddjango-4b2f6ace5789768a5734b017b70b3dec31bb000c.tar.gz
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.
Diffstat (limited to 'django/http')
-rw-r--r--django/http/response.py14
1 files changed, 9 insertions, 5 deletions
diff --git a/django/http/response.py b/django/http/response.py
index fae91b3f05..ce49d78d9b 100644
--- a/django/http/response.py
+++ b/django/http/response.py
@@ -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