From 964c3d55f00f2da10c2a69f3817408a40f9136ec Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sat, 21 Sep 2024 21:44:42 +0200 Subject: [PATCH] Speed up finding the reason if its unset (#9175) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> (cherry picked from commit 756fae80b824bf1606235962bd2b460b63da4da0) --- CHANGES/9175.misc.rst | 1 + aiohttp/web_response.py | 16 +++++++++------- tests/test_web_response.py | 8 ++++++++ 3 files changed, 18 insertions(+), 7 deletions(-) create mode 120000 CHANGES/9175.misc.rst diff --git a/CHANGES/9175.misc.rst b/CHANGES/9175.misc.rst new file mode 120000 index 00000000000..d6a2f2aaaab --- /dev/null +++ b/CHANGES/9175.misc.rst @@ -0,0 +1 @@ +9174.misc.rst \ No newline at end of file diff --git a/aiohttp/web_response.py b/aiohttp/web_response.py index bf184980700..57b3941bcc0 100644 --- a/aiohttp/web_response.py +++ b/aiohttp/web_response.py @@ -42,6 +42,8 @@ from .payload import Payload from .typedefs import JSONEncoder, LooseHeaders +REASON_PHRASES = {http_status.value: http_status.phrase for http_status in HTTPStatus} + __all__ = ("ContentCoding", "StreamResponse", "Response", "json_response") @@ -102,7 +104,7 @@ def __init__( else: self._headers = CIMultiDict() - self.set_status(status, reason) + self._set_status(status, reason) @property def prepared(self) -> bool: @@ -139,13 +141,13 @@ def set_status( assert ( not self.prepared ), "Cannot change the response status code after the headers have been sent" - self._status = int(status) + self._set_status(status, reason) + + def _set_status(self, status: int, reason: Optional[str]) -> None: + self._status = status if reason is None: - try: - reason = HTTPStatus(self._status).phrase - except ValueError: - reason = "" - if "\n" in reason: + reason = REASON_PHRASES.get(self._status, "") + elif "\n" in reason: raise ValueError("Reason cannot contain \\n") self._reason = reason diff --git a/tests/test_web_response.py b/tests/test_web_response.py index ec9522b05a5..080edaf57c3 100644 --- a/tests/test_web_response.py +++ b/tests/test_web_response.py @@ -933,6 +933,14 @@ def test_set_status_with_reason() -> None: assert "Everything is fine!" == resp.reason +def test_set_status_with_empty_reason() -> None: + resp = StreamResponse() + + resp.set_status(200, "") + assert resp.status == 200 + assert resp.reason == "" + + async def test_start_force_close() -> None: req = make_request("GET", "/") resp = StreamResponse()