request.py 1.1 KB

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