From: Tom Christie Date: Sat, 30 Nov 2019 17:43:48 +0000 (+0000) Subject: Add Response.is_error (#574) X-Git-Tag: 0.9.0~35 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=fdaa01275a1b80e54be4423e579f9a19f7c63d8f;p=thirdparty%2Fhttpx.git Add Response.is_error (#574) --- diff --git a/docs/compatibility.md b/docs/compatibility.md index a95c12cd..d652a0ab 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -14,6 +14,7 @@ to the API in our own documentation. The following exceptions apply: but also provide lower-cased versions for API compatibility with `requests`. * `stream=True`. - Streaming responses provide the `.stream()` and `.raw()` byte iterator interfaces, rather than the `.iter_content()` method and the `.raw` socket interface. * `.get`, `.delete`, `.head`, `.options` - These methods do not support `files`, `data`, or `json` arguments. Use `.request` if you need to need to send data using these http methods. +* We don't support `response.is_ok` since the naming is ambiguous there, and might incorrectly imply an equivalence to `response.status_code == codes.OK`. Instead we provide an `.is_error` property. ## Advanced Usage diff --git a/httpx/models.py b/httpx/models.py index e703e2da..5469efcd 100644 --- a/httpx/models.py +++ b/httpx/models.py @@ -846,6 +846,10 @@ class Response: return self._decoder + @property + def is_error(self) -> bool: + return StatusCode.is_error(self.status_code) + @property def is_redirect(self) -> bool: return StatusCode.is_redirect(self.status_code) and "location" in self.headers @@ -861,11 +865,9 @@ class Response: if StatusCode.is_client_error(self.status_code): message = message.format(self, error_type="Client Error") + raise HTTPError(message, response=self) elif StatusCode.is_server_error(self.status_code): message = message.format(self, error_type="Server Error") - else: - message = "" - if message: raise HTTPError(message, response=self) def json(self, **kwargs: typing.Any) -> typing.Union[dict, list]: diff --git a/httpx/status_codes.py b/httpx/status_codes.py index 3be26caf..eda7c562 100644 --- a/httpx/status_codes.py +++ b/httpx/status_codes.py @@ -49,6 +49,10 @@ class StatusCode(IntEnum): StatusCode.PERMANENT_REDIRECT, ) + @classmethod + def is_error(cls, value: int) -> bool: + return 400 <= value <= 599 + @classmethod def is_client_error(cls, value: int) -> bool: return 400 <= value <= 499 diff --git a/tests/models/test_responses.py b/tests/models/test_responses.py index 012d2b74..e7be4872 100644 --- a/tests/models/test_responses.py +++ b/tests/models/test_responses.py @@ -23,6 +23,7 @@ def test_response(): assert response.reason_phrase == "OK" assert response.text == "Hello, world!" assert response.elapsed == datetime.timedelta(0) + assert not response.is_error def test_response_repr():