Skip to content

Commit

Permalink
Speed up finding the reason if its unset (#9175)
Browse files Browse the repository at this point in the history
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
(cherry picked from commit 756fae8)
  • Loading branch information
bdraco authored and patchback[bot] committed Sep 21, 2024
1 parent 0408ba6 commit 964c3d5
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
1 change: 1 addition & 0 deletions CHANGES/9175.misc.rst
16 changes: 9 additions & 7 deletions aiohttp/web_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")


Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand Down
8 changes: 8 additions & 0 deletions tests/test_web_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit 964c3d5

Please sign in to comment.