Skip to content

Commit d411bc5

Browse files
authored
[PR #10043/5255cec backport][3.11] Avoid constructing headers mulitidict twice for web.Response (#10045)
1 parent 3dfd7ae commit d411bc5

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

CHANGES/10043.misc.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improved performance of constructing :class:`aiohttp.web.Response` with headers -- by :user:`bdraco`.

aiohttp/web_response.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,15 @@ def __init__(
8686
status: int = 200,
8787
reason: Optional[str] = None,
8888
headers: Optional[LooseHeaders] = None,
89+
_real_headers: Optional[CIMultiDict[str]] = None,
8990
) -> None:
91+
"""Initialize a new stream response object.
92+
93+
_real_headers is an internal parameter used to pass a pre-populated
94+
headers object. It is used by the `Response` class to avoid copying
95+
the headers when creating a new response object. It is not intended
96+
to be used by external code.
97+
"""
9098
self._body = None
9199
self._keep_alive: Optional[bool] = None
92100
self._chunked = False
@@ -102,7 +110,9 @@ def __init__(
102110
self._body_length = 0
103111
self._state: Dict[str, Any] = {}
104112

105-
if headers is not None:
113+
if _real_headers is not None:
114+
self._headers = _real_headers
115+
elif headers is not None:
106116
self._headers: CIMultiDict[str] = CIMultiDict(headers)
107117
else:
108118
self._headers = CIMultiDict()
@@ -660,7 +670,7 @@ def __init__(
660670
content_type += "; charset=" + charset
661671
real_headers[hdrs.CONTENT_TYPE] = content_type
662672

663-
super().__init__(status=status, reason=reason, headers=real_headers)
673+
super().__init__(status=status, reason=reason, _real_headers=real_headers)
664674

665675
if text is not None:
666676
self.text = text

0 commit comments

Comments
 (0)