Skip to content
Myr

is_informational / is_success / is_redirect / is_client_error / is_server_error (#1854)

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

authored by Tom Christie · committed by GitHub · parent ff9813e · Browse files · 4 files+157 added−32 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+157 added−32 removed

  • tests:+36 added−2 removed
  • other:+121 added−30 removed

4 files+157 added−32 removed

modified:httpx/_client.py+2 added-2 removed
943 unmodified lines
944 for hook in self._event_hooks["response"]:945 hook(response)946 response.history = list(history)947948 if not response.is_redirect:948 if not response.has_redirect_location:949 return response950951 request = self._build_redirect_request(request, response)952 history = history + [response]
686 unmodified lines
1639 await hook(response)16401641 response.history = list(history)16421643 if not response.is_redirect:1643 if not response.has_redirect_location:1644 return response16451646 request = self._build_redirect_request(request, response)1647 history = history + [response]
324 unmodified lines
modified:httpx/_models.py+89 added-13 removed
1398 unmodified lines
13991400 return self._decoder14011402 @property1403 def is_informational(self) -> bool:1404 """1405 A property which is `True` for 1xx status codes, `False` otherwise.1406 """1407 return codes.is_informational(self.status_code)14081409 @property1410 def is_success(self) -> bool:1411 """1412 A property which is `True` for 2xx status codes, `False` otherwise.1413 """1414 return codes.is_success(self.status_code)14151416 @property1417 def is_redirect(self) -> bool:1418 """1419 A property which is `True` for 3xx status codes, `False` otherwise.14201421 Note that not all responses with a 3xx status code indicate a URL redirect.14221423 Use `response.has_redirect_location` to determine responses with a properly1424 formed URL redirection.1425 """1426 return codes.is_redirect(self.status_code)14271428 @property1429 def is_client_error(self) -> bool:1430 """1431 A property which is `True` for 4xx status codes, `False` otherwise.1432 """1433 return codes.is_client_error(self.status_code)14341435 @property1436 def is_server_error(self) -> bool:1437 """1438 A property which is `True` for 5xx status codes, `False` otherwise.1439 """1440 return codes.is_server_error(self.status_code)14411442 @property1443 def is_error(self) -> bool:1444 """1445 A property which is `True` for 4xx and 5xx status codes, `False` otherwise.1446 """1447 return codes.is_error(self.status_code)14481449 @property1407 def is_redirect(self) -> bool:1408 return codes.is_redirect(self.status_code) and "location" in self.headers1450 def has_redirect_location(self) -> bool:1451 """1452 Returns True for 3xx responses with a properly formed URL redirection,1453 `False` otherwise.1454 """1455 return (1456 self.status_code1457 in (1458 # 301 (Cacheable redirect. Method may change to GET.)1459 codes.MOVED_PERMANENTLY,1460 # 302 (Uncacheable redirect. Method may change to GET.)1461 codes.FOUND,1462 # 303 (Client should make a GET or HEAD request.)1463 codes.SEE_OTHER,1464 # 307 (Equiv. 302, but retain method)1465 codes.TEMPORARY_REDIRECT,1466 # 308 (Equiv. 301, but retain method)1467 codes.PERMANENT_REDIRECT,1468 )1469 and "Location" in self.headers1470 )14711472 def raise_for_status(self) -> None:1473 """1474 Raise the `HTTPStatusError` if one occurred.1475 """1414 message = (1415 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"1416 "For more information check: https://httpstatuses.com/{0.status_code}"1417 )14181476 request = self._request1477 if request is None:1478 raise RuntimeError(1479 "Cannot call `raise_for_status` as the request "1480 "instance has not been set on this response."1481 )14821426 if codes.is_client_error(self.status_code):1427 message = message.format(self, error_type="Client Error")1428 raise HTTPStatusError(message, request=request, response=self)1429 elif codes.is_server_error(self.status_code):1430 message = message.format(self, error_type="Server Error")1431 raise HTTPStatusError(message, request=request, response=self)1483 if self.is_success:1484 return14851486 if self.has_redirect_location:1487 message = (1488 "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n"1489 "Redirect location: '{0.headers[location]}'\n"1490 "For more information check: https://httpstatuses.com/{0.status_code}"1491 )1492 else:1493 message = (1494 "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n"1495 "For more information check: https://httpstatuses.com/{0.status_code}"1496 )14971498 status_class = self.status_code // 1001499 error_types = {1500 1: "Informational response",1501 3: "Redirect response",1502 4: "Client error",1503 5: "Server error",1504 }1505 error_type = error_types.get(status_class, "Invalid status code")1506 message = message.format(self, error_type=error_type)1507 raise HTTPStatusError(message, request=request, response=self)15081509 def json(self, **kwargs: typing.Any) -> typing.Any:1510 if self.charset_encoding is None and self.content and len(self.content) > 3:1511 encoding = guess_json_utf(self.content)1512 if encoding is not None:
431 unmodified lines
modified:httpx/_status_codes.py+30 added-15 removed
37 unmodified lines
38 except ValueError:39 return ""4041 @classmethod42 def is_redirect(cls, value: int) -> bool:43 return value in (44 # 301 (Cacheable redirect. Method may change to GET.)45 codes.MOVED_PERMANENTLY,46 # 302 (Uncacheable redirect. Method may change to GET.)47 codes.FOUND,48 # 303 (Client should make a GET or HEAD request.)49 codes.SEE_OTHER,50 # 307 (Equiv. 302, but retain method)51 codes.TEMPORARY_REDIRECT,52 # 308 (Equiv. 301, but retain method)53 codes.PERMANENT_REDIRECT,54 )42 def is_informational(cls, value: int) -> bool:43 """44 Returns `True` for 1xx status codes, `False` otherwise.45 """46 return 100 <= value <= 1994748 @classmethod57 def is_error(cls, value: int) -> bool:58 return 400 <= value <= 59949 def is_success(cls, value: int) -> bool:50 """51 Returns `True` for 2xx status codes, `False` otherwise.52 """53 return 200 <= value <= 2995455 @classmethod56 def is_redirect(cls, value: int) -> bool:57 """58 Returns `True` for 3xx status codes, `False` otherwise.59 """60 return 300 <= value <= 3996162 @classmethod63 def is_client_error(cls, value: int) -> bool:64 """65 Returns `True` for 4xx status codes, `False` otherwise.66 """67 return 400 <= value <= 4996869 @classmethod70 def is_server_error(cls, value: int) -> bool:71 """72 Returns `True` for 5xx status codes, `False` otherwise.73 """74 return 500 <= value <= 5997576 @classmethod77 def is_error(cls, value: int) -> bool:78 """79 Returns `True` for 4xx or 5xx status codes, `False` otherwise.80 """81 return 400 <= value <= 5998283 # informational84 CONTINUE = 100, "Continue"85 SWITCHING_PROTOCOLS = 101, "Switching Protocols"86 PROCESSING = 102, "Processing"
72 unmodified lines
modified:tests/models/test_responses.py+36 added-2 removed
88 unmodified lines
89 # 2xx status codes are not an error.90 response = httpx.Response(200, request=request)91 response.raise_for_status()9293 # 1xx status codes are informational responses.94 response = httpx.Response(101, request=request)95 assert response.is_informational96 with pytest.raises(httpx.HTTPStatusError) as exc_info:97 response.raise_for_status()98 assert str(exc_info.value) == (99 "Informational response '101 Switching Protocols' for url 'https://example.org'\n"100 "For more information check: https://httpstatuses.com/101"101 )102103 # 3xx status codes are redirections.104 headers = {"location": "https://other.org"}105 response = httpx.Response(303, headers=headers, request=request)106 assert response.is_redirect107 with pytest.raises(httpx.HTTPStatusError) as exc_info:108 response.raise_for_status()109 assert str(exc_info.value) == (110 "Redirect response '303 See Other' for url 'https://example.org'\n"111 "Redirect location: 'https://other.org'\n"112 "For more information check: https://httpstatuses.com/303"113 )114115 # 4xx status codes are a client error.116 response = httpx.Response(403, request=request)117 assert response.is_client_error118 assert response.is_error95 with pytest.raises(httpx.HTTPStatusError):119 with pytest.raises(httpx.HTTPStatusError) as exc_info:120 response.raise_for_status()121 assert str(exc_info.value) == (122 "Client error '403 Forbidden' for url 'https://example.org'\n"123 "For more information check: https://httpstatuses.com/403"124 )125126 # 5xx status codes are a server error.127 response = httpx.Response(500, request=request)128 assert response.is_server_error129 assert response.is_error100 with pytest.raises(httpx.HTTPStatusError):130 with pytest.raises(httpx.HTTPStatusError) as exc_info:131 response.raise_for_status()132 assert str(exc_info.value) == (133 "Server error '500 Internal Server Error' for url 'https://example.org'\n"134 "For more information check: https://httpstatuses.com/500"135 )136137 # Calling .raise_for_status without setting a request instance is138 # not valid. Should raise a runtime error.139 response = httpx.Response(200)
805 unmodified lines