curl_cffi.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. from __future__ import annotations
  2. from curl_cffi.requests import AsyncSession, Response
  3. try:
  4. from curl_cffi.requests import CurlMime
  5. has_curl_mime = True
  6. except ImportError:
  7. has_curl_mime = False
  8. try:
  9. from curl_cffi.requests import CurlWsFlag
  10. has_curl_ws = True
  11. except ImportError:
  12. has_curl_ws = False
  13. from typing import AsyncGenerator, Any
  14. from functools import partialmethod
  15. import json
  16. class StreamResponse:
  17. """
  18. A wrapper class for handling asynchronous streaming responses.
  19. Attributes:
  20. inner (Response): The original Response object.
  21. """
  22. def __init__(self, inner: Response) -> None:
  23. """Initialize the StreamResponse with the provided Response object."""
  24. self.inner: Response = inner
  25. async def text(self) -> str:
  26. """Asynchronously get the response text."""
  27. return await self.inner.atext()
  28. def raise_for_status(self) -> None:
  29. """Raise an HTTPError if one occurred."""
  30. self.inner.raise_for_status()
  31. async def json(self, **kwargs) -> Any:
  32. """Asynchronously parse the JSON response content."""
  33. return json.loads(await self.inner.acontent(), **kwargs)
  34. def iter_lines(self) -> AsyncGenerator[bytes, None]:
  35. """Asynchronously iterate over the lines of the response."""
  36. return self.inner.aiter_lines()
  37. def iter_content(self) -> AsyncGenerator[bytes, None]:
  38. """Asynchronously iterate over the response content."""
  39. return self.inner.aiter_content()
  40. async def __aenter__(self):
  41. """Asynchronously enter the runtime context for the response object."""
  42. inner: Response = await self.inner
  43. self.inner = inner
  44. self.request = inner.request
  45. self.status: int = inner.status_code
  46. self.reason: str = inner.reason
  47. self.ok: bool = inner.ok
  48. self.headers = inner.headers
  49. self.cookies = inner.cookies
  50. return self
  51. async def __aexit__(self, *args):
  52. """Asynchronously exit the runtime context for the response object."""
  53. await self.inner.aclose()
  54. class StreamSession(AsyncSession):
  55. """
  56. An asynchronous session class for handling HTTP requests with streaming.
  57. Inherits from AsyncSession.
  58. """
  59. def request(
  60. self, method: str, url: str, **kwargs
  61. ) -> StreamResponse:
  62. if isinstance(kwargs.get("data"), CurlMime):
  63. kwargs["multipart"] = kwargs.pop("data")
  64. """Create and return a StreamResponse object for the given HTTP request."""
  65. return StreamResponse(super().request(method, url, stream=True, **kwargs))
  66. def ws_connect(self, url, *args, **kwargs):
  67. return WebSocket(self, url, **kwargs)
  68. def _ws_connect(self, url, **kwargs):
  69. return super().ws_connect(url, **kwargs)
  70. # Defining HTTP methods as partial methods of the request method.
  71. head = partialmethod(request, "HEAD")
  72. get = partialmethod(request, "GET")
  73. post = partialmethod(request, "POST")
  74. put = partialmethod(request, "PUT")
  75. patch = partialmethod(request, "PATCH")
  76. delete = partialmethod(request, "DELETE")
  77. if has_curl_mime:
  78. class FormData(CurlMime):
  79. def add_field(self, name, data=None, content_type: str = None, filename: str = None) -> None:
  80. self.addpart(name, content_type=content_type, filename=filename, data=data)
  81. else:
  82. class FormData():
  83. def __init__(self) -> None:
  84. raise RuntimeError("CurlMimi in curl_cffi is missing | pip install -U g4f[curl_cffi]")
  85. class WebSocket():
  86. def __init__(self, session, url, **kwargs) -> None:
  87. if not has_curl_ws:
  88. raise RuntimeError("CurlWsFlag in curl_cffi is missing | pip install -U g4f[curl_cffi]")
  89. self.session: StreamSession = session
  90. self.url: str = url
  91. del kwargs["autoping"]
  92. self.options: dict = kwargs
  93. async def __aenter__(self):
  94. self.inner = await self.session._ws_connect(self.url, **self.options)
  95. return self
  96. async def __aexit__(self, *args):
  97. await self.inner.aclose()
  98. async def receive_str(self, **kwargs) -> str:
  99. bytes, _ = await self.inner.arecv()
  100. return bytes.decode(errors="ignore")
  101. async def send_str(self, data: str):
  102. await self.inner.asend(data.encode(), CurlWsFlag.TEXT)