Skip to content

Commit

Permalink
[PR #10043/5255cec backport][3.11] Avoid constructing headers mulitid…
Browse files Browse the repository at this point in the history
…ict twice for ``web.Response`` (#10045)
  • Loading branch information
bdraco authored Nov 25, 2024
1 parent 3dfd7ae commit d411bc5
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGES/10043.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improved performance of constructing :class:`aiohttp.web.Response` with headers -- by :user:`bdraco`.
14 changes: 12 additions & 2 deletions aiohttp/web_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,15 @@ def __init__(
status: int = 200,
reason: Optional[str] = None,
headers: Optional[LooseHeaders] = None,
_real_headers: Optional[CIMultiDict[str]] = None,
) -> None:
"""Initialize a new stream response object.
_real_headers is an internal parameter used to pass a pre-populated
headers object. It is used by the `Response` class to avoid copying
the headers when creating a new response object. It is not intended
to be used by external code.
"""
self._body = None
self._keep_alive: Optional[bool] = None
self._chunked = False
Expand All @@ -102,7 +110,9 @@ def __init__(
self._body_length = 0
self._state: Dict[str, Any] = {}

if headers is not None:
if _real_headers is not None:
self._headers = _real_headers
elif headers is not None:
self._headers: CIMultiDict[str] = CIMultiDict(headers)
else:
self._headers = CIMultiDict()
Expand Down Expand Up @@ -660,7 +670,7 @@ def __init__(
content_type += "; charset=" + charset
real_headers[hdrs.CONTENT_TYPE] = content_type

super().__init__(status=status, reason=reason, headers=real_headers)
super().__init__(status=status, reason=reason, _real_headers=real_headers)

if text is not None:
self.text = text
Expand Down

0 comments on commit d411bc5

Please sign in to comment.