From 4b2f6ace5789768a5734b017b70b3dec31bb000c Mon Sep 17 00:00:00 2001
From: Keryn Knight <keryn@kerynknight.com>
Date: Wed, 9 Feb 2022 19:42:44 +0000
Subject: [PATCH] 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.
---
 django/http/response.py | 14 +++++++++-----
 1 file 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