Int status codes (#92)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Use plain int for response.status_code * Linting
authored by Tom Christie · committed by GitHub · parent 920925c · Browse files · 13 files·+42 added−39 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+42 added−39 removed
- tests:+21 added−3 removed
- other:+21 added−36 removed
Provenance
- Commit
56a7943- Tree
4b18f34- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
920925c
13 files changed+42 added−39 removed
modified:docs/api.md+1 added-1 removed
35 unmodified lines36373839404041424344102 unmodified linesExpand all35 unmodified lines
*An HTTP response.*
* `def __init__(...)`* `.status_code` - **int** *(Typically a `StatusCode` IntEnum.)** `.status_code` - **int*** `.reason_phrase` - **str*** `.protocol` - `"HTTP/2"` or `"HTTP/1.1"`* `.url` - **URL*** `.headers` - **Headers**102 unmodified linesExpand allmodified:docs/index.md+3 added-1 removed
21 unmodified lines22 23 ```python24 >>> import http325 >>> r = http3.get('https://www.example.org/')26+>>> r27+<Response [200 OK]>28 >>> r.status_code27-<StatusCode.OK: 200>29+20030 >>> r.protocol31 'HTTP/2'32 >>> r.headers['content-type']33 'text/html; charset=UTF-8'67 unmodified linesmodified:docs/quickstart.md+8 added-14 removed
13 unmodified lines14 Now, let’s try to get a webpage.15 16 ```python17 >>> r = http3.get('https://httpbin.org/get')18+>>> r19+<Response [200 OK]>20 ```21 22 Similarly, to make an HTTP POST request:23 210 unmodified lines234 235 ```python236 >>> r = http3.get('https://httpbin.org/get')237 >>> r.status_code236-<StatusCode.OK: 200>238+200239 ```240 239-The status code is an integer enum, meaning that the Python representation gives240-use some descriptive information, but the value itself can be used as a regular integer.241-242-```python243->>> r.status_code == 200244-True245-```246-241 HTTP3 also includes an easy shortcut for accessing status codes by their text phrase.242 243 ```python250->>> r.status_code == requests.codes.OK244+>>> r.status_code == http3.codes.OK245 True246 ```247 248 We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):249 250 ```python251 >>> not_found = http3.get('https://httpbin.org/status/404')252 >>> not_found.status_code259-<StatusCode.NOT_FOUND: 404>253+404254 >>> not_found.raise_for_status()255 Traceback (most recent call last):256 File "/Users/tomchristie/GitHub/encode/httpcore/http3/models.py", line 776, in raise_for_status257 raise HttpError(message)83 unmodified lines341 >>> r = http3.get('http://github.com/')342 >>> r.url343 URL('https://github.com/')344 >>> r.status_code351-<StatusCode.OK: 200>345+200346 >>> r.history353-[<Response [301]>]347+[<Response [301 Moved Permanently]>]348 ```349 350 You can modify the default redirection handling with the allow_redirects parameter:351 11 unmodified lines363 >>> r = http3.head('http://github.com/', allow_redirects=True)364 >>> r.url365 'https://github.com/'366 >>> r.history373-[<Response [301]>]367+[<Response [301 Moved Permanently]>]368 ```369 370 ## Timeouts371 10 unmodified linesmodified:http3/dispatch/http11.py-2 removed
65 unmodified lines66 if isinstance(event, h11.InformationalResponse):67 event = await self._receive_event(timeout)68 69 assert isinstance(event, h11.Response)70- reason_phrase = event.reason.decode("ascii", errors="ignore")70 status_code = event.status_code71 headers = event.headers72 content = self._body_iter(timeout)73 74 return AsyncResponse(75 status_code=status_code,77- reason_phrase=reason_phrase,76 protocol="HTTP/1.1",77 headers=headers,78 content=content,79 on_close=self.response_closed,46 unmodified linesmodified:http3/dispatch/threaded.py-1 removed
62 unmodified lines63 await concurrency_backend.run_in_threadpool(sync_response.close)64 65 return AsyncResponse(66 status_code=sync_response.status_code,67- reason_phrase=sync_response.reason_phrase,67 protocol=sync_response.protocol,68 headers=sync_response.headers,69 content=async_content,70 on_close=async_on_close,26 unmodified linesmodified:http3/client.py-1 removed
607 unmodified lines608 concurrency_backend.run(async_response.on_close)609 610 response = Response(611 status_code=async_response.status_code,612- reason_phrase=async_response.reason_phrase,612 protocol=async_response.protocol,613 headers=async_response.headers,614 content=sync_content,615 on_close=sync_on_close,244 unmodified linesmodified:http3/models.py+6 added-8 removed
656 unmodified lines657 def __init__(658 self,659 status_code: int,660 *,661- reason_phrase: str = None,661 protocol: str = None,662 headers: HeaderTypes = None,663 request: BaseRequest = None,664 on_close: typing.Callable = None,665 ):667- self.status_code = StatusCode.enum_or_int(status_code)668- self.reason_phrase = StatusCode.get_reason_phrase(status_code)666+ self.status_code = status_code667 self.protocol = protocol668 self.headers = Headers(headers)669 670 self.request = request671 self.on_close = on_close672 self.next = None # typing.Optional[typing.Callable]673 674 @property675+ def reason_phrase(self) -> str:676+ return StatusCode.get_reason_phrase(self.status_code)677+678+ @property679 def url(self) -> typing.Optional[URL]:680 """681 Returns the URL for which the request was made.682 125 unmodified lines808 self._cookies.extract_cookies(self)809 return self._cookies810 811 def __repr__(self) -> str:810- return f"<Response({self.status_code}, {self.reason_phrase!r})>"812+ return f"<Response [{self.status_code} {self.reason_phrase}])>"813 814 815 class AsyncResponse(BaseResponse):816 def __init__(817 self,818 status_code: int,819 *,818- reason_phrase: str = None,820 protocol: str = None,821 headers: HeaderTypes = None,822 content: AsyncResponseContent = None,823 on_close: typing.Callable = None,1 unmodified line825 history: typing.List["BaseResponse"] = None,826 ):827 super().__init__(828 status_code=status_code,828- reason_phrase=reason_phrase,829 protocol=protocol,830 headers=headers,831 request=request,832 on_close=on_close,62 unmodified lines895 def __init__(896 self,897 status_code: int,898 *,899- reason_phrase: str = None,899 protocol: str = None,900 headers: HeaderTypes = None,901 content: ResponseContent = None,902 on_close: typing.Callable = None,1 unmodified line904 history: typing.List["BaseResponse"] = None,905 ):906 super().__init__(907 status_code=status_code,909- reason_phrase=reason_phrase,908 protocol=protocol,909 headers=headers,910 request=request,911 on_close=on_close,234 unmodified linesmodified:http3/status_codes.py-7 removed
24 unmodified lines25 def __str__(self) -> str:26 return str(self.value)27 28 @classmethod29- def enum_or_int(cls, value: int) -> int:30- try:31- return StatusCode(value)32- except ValueError:33- return value34-35- @classmethod29 def get_reason_phrase(cls, value: int) -> str:30 try:31 return StatusCode(value).phrase # type: ignore32 except ValueError:94 unmodified linesmodified:tests/client/test_async_client.py+1 added-1 removed
10 unmodified lines11 assert response.status_code == 20012 assert response.text == "Hello, world!"13 assert response.protocol == "HTTP/1.1"14 assert response.headers15- assert repr(response) == "<Response(200, 'OK')>"15+ assert repr(response) == "<Response [200 OK])>"16 17 18 @pytest.mark.asyncio19 async def test_post(server):115 unmodified linesmodified:tests/client/test_client.py+1 added-1 removed
35 unmodified lines36 assert response.encoding == "iso-8859-1"37 assert response.request.url == http3.URL(url)38 assert response.headers39 assert response.is_redirect is False40- assert repr(response) == "<Response(200, 'OK')>"40+ assert repr(response) == "<Response [200 OK])>"41 42 43 @threadpool44 def test_post(server):99 unmodified linesmodified:tests/models/test_responses.py+1 added-1 removed
20 unmodified lines21 22 23 def test_response_repr():24 response = http3.Response(200, content=b"Hello, world!")25- assert repr(response) == "<Response(200, 'OK')>"25+ assert repr(response) == "<Response [200 OK])>"26 27 28 def test_response_content_type_encoding():29 """223 unmodified linesadded:tests/test_status_codes.py+18 added
1+import http32+3+4+def test_status_code_as_int():5+ assert http3.codes.NOT_FOUND == 4046+ assert str(http3.codes.NOT_FOUND) == "404"7+8+9+def test_lowercase_status_code():10+ assert http3.codes.not_found == 40411+12+13+def test_reason_phrase_for_status_code():14+ assert http3.codes.get_reason_phrase(404) == "Not Found"15+16+17+def test_reason_phrase_for_unknown_status_code():18+ assert http3.codes.get_reason_phrase(499) == ""modified:README.md+3 added-1 removed
19 unmodified lines20 21 ```python22 >>> import http323 >>> r = http3.get('https://www.example.org/')24+>>> r25+<Response [200 OK]>26 >>> r.status_code25-<StatusCode.OK: 200>27+20028 >>> r.protocol29 'HTTP/2'30 >>> r.headers['content-type']31 'text/html; charset=UTF-8'72 unmodified lines