Skip to content
Myr

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

13 files+42 added−39 removed

modified:docs/api.md+1 added-1 removed
modified:docs/index.md+3 added-1 removed
21 unmodified lines
2223```python24>>> import http325>>> r = http3.get('https://www.example.org/')26>>> r27<Response [200 OK]>28>>> r.status_code27<StatusCode.OK: 200>2920030>>> r.protocol31'HTTP/2'32>>> r.headers['content-type']33'text/html; charset=UTF-8'
67 unmodified lines
modified:docs/quickstart.md+8 added-14 removed
13 unmodified lines
14Now, let’s try to get a webpage.1516```python17>>> r = http3.get('https://httpbin.org/get')18>>> r19<Response [200 OK]>20```2122Similarly, to make an HTTP POST request:23
210 unmodified lines
234235```python236>>> r = http3.get('https://httpbin.org/get')237>>> r.status_code236<StatusCode.OK: 200>238200239```240239The status code is an integer enum, meaning that the Python representation gives240use some descriptive information, but the value itself can be used as a regular integer.241242```python243>>> r.status_code == 200244True245```246241HTTP3 also includes an easy shortcut for accessing status codes by their text phrase.242243```python250>>> r.status_code == requests.codes.OK244>>> r.status_code == http3.codes.OK245True246```247248We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):249250```python251>>> not_found = http3.get('https://httpbin.org/status/404')252>>> not_found.status_code259<StatusCode.NOT_FOUND: 404>253404254>>> not_found.raise_for_status()255Traceback (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 lines
341>>> r = http3.get('http://github.com/')342>>> r.url343URL('https://github.com/')344>>> r.status_code351<StatusCode.OK: 200>345200346>>> r.history353[<Response [301]>]347[<Response [301 Moved Permanently]>]348```349350You can modify the default redirection handling with the allow_redirects parameter:351
11 unmodified lines
363>>> 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```369370## Timeouts371
10 unmodified lines
modified:http3/dispatch/http11.py-2 removed
65 unmodified lines
66 if isinstance(event, h11.InformationalResponse):67 event = await self._receive_event(timeout)6869 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)7374 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 lines
modified:http3/dispatch/threaded.py-1 removed
62 unmodified lines
63 await concurrency_backend.run_in_threadpool(sync_response.close)6465 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 lines
modified:http3/client.py-1 removed
607 unmodified lines
608 concurrency_backend.run(async_response.on_close)609610 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 lines
modified:http3/models.py+6 added-8 removed
656 unmodified lines
657 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)669670 self.request = request671 self.on_close = on_close672 self.next = None # typing.Optional[typing.Callable]673674 @property675 def reason_phrase(self) -> str:676 return StatusCode.get_reason_phrase(self.status_code)677678 @property679 def url(self) -> typing.Optional[URL]:680 """681 Returns the URL for which the request was made.682
125 unmodified lines
808 self._cookies.extract_cookies(self)809 return self._cookies810811 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}])>"813814815class 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 line
825 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 lines
895 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 line
904 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 lines
modified:http3/status_codes.py-7 removed
24 unmodified lines
25 def __str__(self) -> str:26 return str(self.value)2728 @classmethod29 def enum_or_int(cls, value: int) -> int:30 try:31 return StatusCode(value)32 except ValueError:33 return value3435 @classmethod29 def get_reason_phrase(cls, value: int) -> str:30 try:31 return StatusCode(value).phrase # type: ignore32 except ValueError:
94 unmodified lines
modified:tests/client/test_async_client.py+1 added-1 removed
10 unmodified lines
11 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])>"161718@pytest.mark.asyncio19async def test_post(server):
115 unmodified lines
modified:tests/client/test_client.py+1 added-1 removed
35 unmodified lines
36 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])>"414243@threadpool44def test_post(server):
99 unmodified lines
modified:tests/models/test_responses.py+1 added-1 removed
20 unmodified lines
212223def 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])>"262728def test_response_content_type_encoding():29 """
223 unmodified lines
added:tests/test_status_codes.py+18 added
1import http3234def test_status_code_as_int():5 assert http3.codes.NOT_FOUND == 4046 assert str(http3.codes.NOT_FOUND) == "404"789def test_lowercase_status_code():10 assert http3.codes.not_found == 404111213def test_reason_phrase_for_status_code():14 assert http3.codes.get_reason_phrase(404) == "Not Found"151617def test_reason_phrase_for_unknown_status_code():18 assert http3.codes.get_reason_phrase(499) == ""
modified:README.md+3 added-1 removed
19 unmodified lines
2021```python22>>> import http323>>> r = http3.get('https://www.example.org/')24>>> r25<Response [200 OK]>26>>> r.status_code25<StatusCode.OK: 200>2720028>>> r.protocol29'HTTP/2'30>>> r.headers['content-type']31'text/html; charset=UTF-8'
72 unmodified lines