raise_for_status.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from __future__ import annotations
  2. from typing import Union
  3. from aiohttp import ClientResponse
  4. from requests import Response as RequestsResponse
  5. from ..errors import ResponseStatusError, RateLimitError
  6. from . import Response, StreamResponse
  7. class CloudflareError(ResponseStatusError):
  8. ...
  9. def is_cloudflare(text: str) -> bool:
  10. return '<div id="cf-please-wait">' in text or "<title>Just a moment...</title>" in text
  11. def is_openai(text: str) -> bool:
  12. return "<p>Unable to load site</p>" in text
  13. async def raise_for_status_async(response: Union[StreamResponse, ClientResponse], message: str = None):
  14. if response.status in (429, 402):
  15. raise RateLimitError(f"Response {response.status}: Rate limit reached")
  16. message = await response.text() if not response.ok and message is None else message
  17. if response.status == 403 and is_cloudflare(message):
  18. raise CloudflareError(f"Response {response.status}: Cloudflare detected")
  19. elif response.status == 403 and is_openai(message):
  20. raise ResponseStatusError(f"Response {response.status}: Bot are detected")
  21. elif not response.ok:
  22. raise ResponseStatusError(f"Response {response.status}: {message}")
  23. def raise_for_status(response: Union[Response, StreamResponse, ClientResponse, RequestsResponse], message: str = None):
  24. if hasattr(response, "status"):
  25. return raise_for_status_async(response, message)
  26. if response.status_code in (429, 402):
  27. raise RateLimitError(f"Response {response.status_code}: Rate limit reached")
  28. elif response.status_code == 403 and is_cloudflare(response.text):
  29. raise CloudflareError(f"Response {response.status_code}: Cloudflare detected")
  30. elif not response.ok:
  31. raise ResponseStatusError(f"Response {response.status_code}: {response.text if message is None else message}")