Single consistent name for status codes (#1088)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Single consistent name for status codes * Gentle deprecation for httpx.StatusCode
authored by Tom Christie · committed by GitHub · parent 2e60e14 · Browse files · 4 files·+57 added−17 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+57 added−17 removed
- tests:+21 added−0 removed
- other:+36 added−17 removed
Provenance
- Commit
35f09d1- Tree
d1480c6- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
2e60e14
4 files changed+57 added−17 removed
modified:httpx/__init__.py+1 added-1 removed
78 unmodified lines79 "RequestBodyUnavailable",80 "ResponseClosed",81 "ResponseNotRead",82 "RequestNotRead",83+ "StatusCode",84 "StreamConsumed",85 "StreamError",86 "ProxyError",87 "TimeoutException",2 unmodified lines90 "WriteTimeout",91 "URL",92 "URLLib3Transport",93 "URLLib3ProxyTransport",93- "StatusCode",94 "Cookies",95 "Headers",96 "QueryParams",97 "Request",4 unmodified linesmodified:httpx/_models.py+6 added-6 removed
28 unmodified lines29 ResponseClosed,30 ResponseNotRead,31 StreamConsumed,32 )33-from ._status_codes import StatusCode33+from ._status_codes import codes34 from ._types import (35 CookieTypes,36 HeaderTypes,37 PrimitiveData,621 unmodified lines659 return self._elapsed660 661 @property662 def reason_phrase(self) -> str:663- return StatusCode.get_reason_phrase(self.status_code)663+ return codes.get_reason_phrase(self.status_code)664 665 @property666 def url(self) -> typing.Optional[URL]:667 """89 unmodified lines757 return self._decoder758 759 @property760 def is_error(self) -> bool:761- return StatusCode.is_error(self.status_code)761+ return codes.is_error(self.status_code)762 763 @property764 def is_redirect(self) -> bool:765- return StatusCode.is_redirect(self.status_code) and "location" in self.headers765+ return codes.is_redirect(self.status_code) and "location" in self.headers766 767 def raise_for_status(self) -> None:768 """769 Raise the `HTTPStatusError` if one occurred.2 unmodified lines772 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"773 "For more information check: https://httpstatuses.com/{0.status_code}"774 )775 776- if StatusCode.is_client_error(self.status_code):776+ if codes.is_client_error(self.status_code):777 message = message.format(self, error_type="Client Error")778 raise HTTPStatusError(message, response=self)779- elif StatusCode.is_server_error(self.status_code):779+ elif codes.is_server_error(self.status_code):780 message = message.format(self, error_type="Server Error")781 raise HTTPStatusError(message, response=self)782 783 def json(self, **kwargs: typing.Any) -> typing.Any:352 unmodified linesmodified:httpx/_status_codes.py+29 added-10 removed
1+import warnings2 from enum import IntEnum3 4 4-class StatusCode(IntEnum):5+class codes(IntEnum):6 """HTTP status codes and reason phrases7 Status codes from the following RFCs are all observed:8 * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 26169 * RFC 6585: Additional HTTP Status Codes7 unmodified lines17 * RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0)18 * RFC 7725: An HTTP Status Code to Report Legal Obstacles19 """20 20- def __new__(cls, value: int, phrase: str = "") -> "StatusCode":21+ def __new__(cls, value: int, phrase: str = "") -> "codes":22 obj = int.__new__(cls, value) # type: ignore23 obj._value_ = value24 25 obj.phrase = phrase4 unmodified lines30 31 @classmethod32 def get_reason_phrase(cls, value: int) -> str:33 try:33- return StatusCode(value).phrase # type: ignore34+ return codes(value).phrase # type: ignore35 except ValueError:36 return ""37 38 @classmethod39 def is_redirect(cls, value: int) -> bool:40 return value in (41 # 301 (Cacheable redirect. Method may change to GET.)41- StatusCode.MOVED_PERMANENTLY,42+ codes.MOVED_PERMANENTLY,43 # 302 (Uncacheable redirect. Method may change to GET.)43- StatusCode.FOUND,44+ codes.FOUND,45 # 303 (Client should make a GET or HEAD request.)45- StatusCode.SEE_OTHER,46+ codes.SEE_OTHER,47 # 307 (Equiv. 302, but retain method)47- StatusCode.TEMPORARY_REDIRECT,48+ codes.TEMPORARY_REDIRECT,49 # 308 (Equiv. 301, but retain method)49- StatusCode.PERMANENT_REDIRECT,50+ codes.PERMANENT_REDIRECT,51 )52 53 @classmethod54 def is_error(cls, value: int) -> bool:77 unmodified lines132 NOT_EXTENDED = 510, "Not Extended"133 NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required"134 135 135-codes = StatusCode136-136 # Include lower-case styles for `requests` compatibility.137 for code in codes:138 setattr(codes, code._name_.lower(), int(code))139+140+141+class StatusCodeCompat:142+ def __call__(self, *args, **kwargs): # type: ignore143+ message = "`httpx.StatusCode` is deprecated. Use `httpx.codes` instead."144+ warnings.warn(message, DeprecationWarning)145+ return codes(*args, **kwargs)146+147+ def __getattr__(self, attr): # type: ignore148+ message = "`httpx.StatusCode` is deprecated. Use `httpx.codes` instead."149+ warnings.warn(message, DeprecationWarning)150+ return getattr(codes, attr)151+152+ def __getitem__(self, item): # type: ignore153+ message = "`httpx.StatusCode` is deprecated. Use `httpx.codes` instead."154+ warnings.warn(message, DeprecationWarning)155+ return codes[item]156+157+158+StatusCode = StatusCodeCompat()modified:tests/test_status_codes.py+21 added
1+import pytest2+3 import httpx4 5 6 def test_status_code_as_int():7 assert httpx.codes.NOT_FOUND == 4048 assert str(httpx.codes.NOT_FOUND) == "404"9 10 11+def test_status_code_value_lookup():12+ assert httpx.codes(404) == 40413+14+15+def test_status_code_phrase_lookup():16+ assert httpx.codes["NOT_FOUND"] == 40417+18+19 def test_lowercase_status_code():20 assert httpx.codes.not_found == 404 # type: ignore21 22 2 unmodified lines25 26 27 def test_reason_phrase_for_unknown_status_code():28 assert httpx.codes.get_reason_phrase(499) == ""29+30+31+def test_deprecated_status_code_class():32+ with pytest.warns(DeprecationWarning):33+ assert httpx.StatusCode.NOT_FOUND == 40434+35+ with pytest.warns(DeprecationWarning):36+ assert httpx.StatusCode(404) == 40437+38+ with pytest.warns(DeprecationWarning):39+ assert httpx.StatusCode["NOT_FOUND"] == 404