request.py 928 B

123456789101112131415161718192021222324252627282930313233343536
  1. from typing import Any
  2. import requests
  3. class RequestHTTPError(requests.HTTPError):
  4. """Exception raised when an error occurs in a request with details."""
  5. def __init__(self, *args, detail=None, **kwargs):
  6. super().__init__(*args, **kwargs)
  7. self.detail = detail
  8. def __str__(self) -> str:
  9. s = super().__str__()
  10. if self.detail is not None:
  11. s += f'\nDetails: {self.detail}'
  12. return s
  13. def send_request(
  14. session: requests.Session,
  15. method: str,
  16. url: str,
  17. timeout: int = 10,
  18. **kwargs: Any,
  19. ) -> requests.Response:
  20. response = session.request(method, url, **kwargs)
  21. try:
  22. response.raise_for_status()
  23. except requests.HTTPError as e:
  24. try:
  25. _json = response.json()
  26. except requests.JSONDecodeError:
  27. raise e
  28. raise RequestHTTPError(e, detail=_json.get('detail')) from e
  29. return response