Skip to content
Myr

Status code tweaks (#77)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Add top-level API * Add tests for top-level API * Further work towards parallel support * StatusCode tweaks * Drop erronous commit

authored by Tom Christie · committed by GitHub · parent c9bb39a · Browse files · 7 files+140 added−42 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+140 added−42 removed

  • tests:+4 added−2 removed
  • other:+136 added−40 removed

7 files+140 added−42 removed

modified:httpcore/__init__.py+1 added-1 removed
28 unmodified lines
29 WriteTimeout,30)31from .interfaces import BaseReader, BaseWriter, ConcurrencyBackend, Dispatcher, Protocol32from .models import URL, Cookies, Headers, Origin, QueryParams, Request, Response33from .status_codes import codes33from .status_codes import StatusCode, codes3435__version__ = "0.3.0"
modified:httpcore/models.py+7 added-26 removed
24 unmodified lines
25 ResponseClosed,26 ResponseNotRead,27 StreamConsumed,28)29from .status_codes import codes30from .utils import (31 get_reason_phrase,32 is_known_encoding,33 normalize_header_key,34 normalize_header_value,35)29from .status_codes import StatusCode30from .utils import is_known_encoding, normalize_header_key, normalize_header_value3132URLTypes = typing.Union["URL", str]3334QueryParamTypes = typing.Union[
537 unmodified lines
572 on_close: typing.Callable = None,573 request: Request = None,574 history: typing.List["Response"] = None,575 ):581 try:582 # Use a StatusCode IntEnum if possible, for a nicer representation.583 self.status_code = codes(status_code) # type: int584 except ValueError:585 self.status_code = status_code586 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)576 self.status_code = StatusCode.enum_or_int(status_code)577 self.reason_phrase = StatusCode.get_reason_phrase(status_code)578 self.protocol = protocol579 self.headers = Headers(headers)580581 if isinstance(content, bytes):
156 unmodified lines
738 await self.on_close()739740 @property741 def is_redirect(self) -> bool:751 return (752 self.status_code753 in (754 codes.MOVED_PERMANENTLY,755 codes.FOUND,756 codes.SEE_OTHER,757 codes.TEMPORARY_REDIRECT,758 codes.PERMANENT_REDIRECT,759 )760 and "location" in self.headers761 )742 return StatusCode.is_redirect(self.status_code) and "location" in self.headers743744 def raise_for_status(self) -> None:745 """746 Raise the `HttpError` if one occurred.
2 unmodified lines
749 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"750 "For more information check: https://httpstatuses.com/{0.status_code}"751 )752772 if 400 <= self.status_code < 500:753 if StatusCode.is_client_error(self.status_code):754 message = message.format(self, error_type="Client Error")774 elif 500 <= self.status_code < 600:755 elif StatusCode.is_server_error(self.status_code):756 message = message.format(self, error_type="Server Error")757 else:758 message = ""759
277 unmodified lines
modified:httpcore/status_codes.py+128 added-2 removed
1from http import HTTPStatus1from enum import IntEnum23codes = HTTPStatus34class StatusCode(IntEnum):5 """HTTP status codes and reason phrases6 Status codes from the following RFCs are all observed:7 * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 26168 * RFC 6585: Additional HTTP Status Codes9 * RFC 3229: Delta encoding in HTTP10 * RFC 4918: HTTP Extensions for WebDAV, obsoletes 251811 * RFC 5842: Binding Extensions to WebDAV12 * RFC 7238: Permanent Redirect13 * RFC 2295: Transparent Content Negotiation in HTTP14 * RFC 2774: An HTTP Extension Framework15 * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2)16 """1718 def __new__(cls, value: int, phrase: str = "") -> "StatusCode":19 obj = int.__new__(cls, value) # type: ignore20 obj._value_ = value2122 obj.phrase = phrase23 return obj2425 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 @classmethod36 def get_reason_phrase(cls, value: int) -> str:37 try:38 return StatusCode(value).phrase # type: ignore39 except ValueError:40 return ""4142 @classmethod43 def is_redirect(cls, value: int) -> bool:44 return value in (45 StatusCode.MOVED_PERMANENTLY, # 301 (Cacheable redirect. Method may change to GET.)46 StatusCode.FOUND, # 302 (Uncacheable redirect. Method may change to GET.)47 StatusCode.SEE_OTHER, # 303 (Client should make a GET or HEAD request.)48 StatusCode.TEMPORARY_REDIRECT, # 307 (Equiv. 302, but retain method)49 StatusCode.PERMANENT_REDIRECT, # 308 (Equiv. 301, but retain method)50 )5152 @classmethod53 def is_client_error(cls, value: int) -> bool:54 return value >= 400 and value <= 4995556 @classmethod57 def is_server_error(cls, value: int) -> bool:58 return value >= 500 and value <= 5995960 # informational61 CONTINUE = 100, "Continue"62 SWITCHING_PROTOCOLS = 101, "Switching Protocols"63 PROCESSING = 102, "Processing"6465 # success66 OK = 200, "OK"67 CREATED = 201, "Created"68 ACCEPTED = 202, "Accepted"69 NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information"70 NO_CONTENT = 204, "No Content"71 RESET_CONTENT = 205, "Reset Content"72 PARTIAL_CONTENT = 206, "Partial Content"73 MULTI_STATUS = 207, "Multi-Status"74 ALREADY_REPORTED = 208, "Already Reported"75 IM_USED = 226, "IM Used"7677 # redirection78 MULTIPLE_CHOICES = 300, "Multiple Choices"79 MOVED_PERMANENTLY = 301, "Moved Permanently"80 FOUND = 302, "Found"81 SEE_OTHER = 303, "See Other"82 NOT_MODIFIED = 304, "Not Modified"83 USE_PROXY = 305, "Use Proxy"84 TEMPORARY_REDIRECT = 307, "Temporary Redirect"85 PERMANENT_REDIRECT = 308, "Permanent Redirect"8687 # client error88 BAD_REQUEST = 400, "Bad Request"89 UNAUTHORIZED = 401, "Unauthorized"90 PAYMENT_REQUIRED = 402, "Payment Required"91 FORBIDDEN = 403, "Forbidden"92 NOT_FOUND = 404, "Not Found"93 METHOD_NOT_ALLOWED = 405, "Method Not Allowed"94 NOT_ACCEPTABLE = 406, "Not Acceptable"95 PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required"96 REQUEST_TIMEOUT = 408, "Request Timeout"97 CONFLICT = 409, "Conflict"98 GONE = 410, "Gone"99 LENGTH_REQUIRED = 411, "Length Required"100 PRECONDITION_FAILED = 412, "Precondition Failed"101 REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large"102 REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long"103 UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type"104 REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable"105 EXPECTATION_FAILED = 417, "Expectation Failed"106 MISDIRECTED_REQUEST = 421, "Misdirected Request"107 UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity"108 LOCKED = 423, "Locked"109 FAILED_DEPENDENCY = 424, "Failed Dependency"110 UPGRADE_REQUIRED = 426, "Upgrade Required"111 PRECONDITION_REQUIRED = 428, "Precondition Required"112 TOO_MANY_REQUESTS = 429, "Too Many Requests"113 REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large"114115 # server errors116 INTERNAL_SERVER_ERROR = 500, "Internal Server Error"117 NOT_IMPLEMENTED = 501, "Not Implemented"118 BAD_GATEWAY = 502, "Bad Gateway"119 SERVICE_UNAVAILABLE = 503, "Service Unavailable"120 GATEWAY_TIMEOUT = 504, "Gateway Timeout"121 HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported"122 VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates"123 INSUFFICIENT_STORAGE = 507, "Insufficient Storage"124 LOOP_DETECTED = 508, "Loop Detected"125 NOT_EXTENDED = 510, "Not Extended"126 NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required"127128129codes = StatusCode
modified:httpcore/utils.py-11 removed
1import codecs2import http2import typing345def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:
13 unmodified lines
19 return value20 return value.encode(encoding or "ascii")212224def get_reason_phrase(status_code: int) -> str:25 """26 Return an HTTP reason phrase such as "OK" for 200, or "Not Found" for 404.27 """28 try:29 return http.HTTPStatus(status_code).phrase30 except ValueError as exc:31 return ""323323def is_known_encoding(encoding: str) -> bool:24 """25 Return `True` if `encoding` is a known codec.26 """
5 unmodified lines
modified:tests/dispatch/test_connections.py+3 added-1 removed
12 unmodified lines
1314@pytest.mark.asyncio15async def test_post(server):16 conn = HTTPConnection(origin="http://127.0.0.1:8000/")17 response = await conn.request("GET", "http://127.0.0.1:8000/", data=b"Hello, world!")17 response = await conn.request(18 "GET", "http://127.0.0.1:8000/", data=b"Hello, world!"19 )20 assert response.status_code == 200212223@pytest.mark.asyncio
19 unmodified lines
modified:tests/dispatch/utils.py+1 added-1 removed
105 unmodified lines
106 request = Request(method, url, headers=headers, data=data)107 response = self.app(request)108109 # Write the response to the buffer.110 status_code_bytes = str(int(response.status_code)).encode("ascii")110 status_code_bytes = str(response.status_code).encode("ascii")111 response_headers = [(b":status", status_code_bytes)] + response.headers.raw112113 self.conn.send_headers(stream_id, response_headers)114 self.conn.send_data(stream_id, response.content, end_stream=True)
1 unmodified line
added:tests/test_parallel.py