request.py 988 B

1234567891011121314151617181920212223242526272829303132333435363738
  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, timeout=timeout, **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(
  29. e, response=e.response, detail=_json.get('detail')
  30. ) from e
  31. return response