From: Tom Christie Date: Thu, 18 Apr 2019 10:41:13 +0000 (+0100) Subject: Add response.reason X-Git-Tag: 0.1.0~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=fc7cf9def62cf66e061f717c44f24c2ec4d3fd90;p=thirdparty%2Fhttpx.git Add response.reason --- diff --git a/httpcore/connections.py b/httpcore/connections.py index 205482e8..16f91408 100644 --- a/httpcore/connections.py +++ b/httpcore/connections.py @@ -68,11 +68,12 @@ class Connection: if isinstance(event, h11.InformationalResponse): event = await self._receive_event() assert isinstance(event, h11.Response) + reason = event.reason.decode('latin1') status_code = event.status_code headers = event.headers body = self._body_iter() return Response( - status_code=status_code, headers=headers, body=body, on_close=self._release + status_code=status_code, reason=reason, headers=headers, body=body, on_close=self._release ) async def _body_iter(self) -> typing.AsyncIterator[bytes]: diff --git a/httpcore/datastructures.py b/httpcore/datastructures.py index 5f84b466..49f85bdc 100644 --- a/httpcore/datastructures.py +++ b/httpcore/datastructures.py @@ -1,3 +1,4 @@ +import http import typing from urllib.parse import urlsplit @@ -122,11 +123,19 @@ class Response: self, status_code: int, *, + reason: typing.Optional[str] = None, headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (), body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"", on_close: typing.Callable = None, ): self.status_code = status_code + if not reason: + try: + self.reason = http.HTTPStatus(status_code).phrase + except ValueError as exc: + self.reason = "" + else: + self.reason = reason self.headers = list(headers) self.on_close = on_close self.is_closed = False diff --git a/tests/test_responses.py b/tests/test_responses.py index ae754b40..3efef890 100644 --- a/tests/test_responses.py +++ b/tests/test_responses.py @@ -24,6 +24,7 @@ http = MockHTTP() async def test_request(): response = await http.request("GET", "http://example.com") assert response.status_code == 200 + assert response.reason == "OK" assert response.body == b"Hello, world!" assert response.is_closed @@ -112,3 +113,9 @@ async def test_cannot_read_after_response_closed(): with pytest.raises(httpcore.ResponseClosed): await response.read() + + +def test_unknown_status_code(): + response = httpcore.Response(600) + assert response.status_code == 600 + assert response.reason == ""