requests_curl_cffi.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from __future__ import annotations
  2. from curl_cffi.requests import AsyncSession, Response
  3. from typing import AsyncGenerator, Any
  4. from functools import partialmethod
  5. import json
  6. class StreamResponse:
  7. """
  8. A wrapper class for handling asynchronous streaming responses.
  9. Attributes:
  10. inner (Response): The original Response object.
  11. """
  12. def __init__(self, inner: Response) -> None:
  13. """Initialize the StreamResponse with the provided Response object."""
  14. self.inner: Response = inner
  15. async def text(self) -> str:
  16. """Asynchronously get the response text."""
  17. return await self.inner.atext()
  18. def raise_for_status(self) -> None:
  19. """Raise an HTTPError if one occurred."""
  20. self.inner.raise_for_status()
  21. async def json(self, **kwargs) -> Any:
  22. """Asynchronously parse the JSON response content."""
  23. return json.loads(await self.inner.acontent(), **kwargs)
  24. async def iter_lines(self) -> AsyncGenerator[bytes, None]:
  25. """Asynchronously iterate over the lines of the response."""
  26. async for line in self.inner.aiter_lines():
  27. yield line
  28. async def iter_content(self) -> AsyncGenerator[bytes, None]:
  29. """Asynchronously iterate over the response content."""
  30. async for chunk in self.inner.aiter_content():
  31. yield chunk
  32. async def __aenter__(self):
  33. """Asynchronously enter the runtime context for the response object."""
  34. inner: Response = await self.inner
  35. self.inner = inner
  36. self.request = inner.request
  37. self.status_code: int = inner.status_code
  38. self.reason: str = inner.reason
  39. self.ok: bool = inner.ok
  40. self.headers = inner.headers
  41. self.cookies = inner.cookies
  42. return self
  43. async def __aexit__(self, *args):
  44. """Asynchronously exit the runtime context for the response object."""
  45. await self.inner.aclose()
  46. class StreamSession(AsyncSession):
  47. """
  48. An asynchronous session class for handling HTTP requests with streaming.
  49. Inherits from AsyncSession.
  50. """
  51. def request(
  52. self, method: str, url: str, **kwargs
  53. ) -> StreamResponse:
  54. """Create and return a StreamResponse object for the given HTTP request."""
  55. return StreamResponse(super().request(method, url, stream=True, **kwargs))
  56. # Defining HTTP methods as partial methods of the request method.
  57. head = partialmethod(request, "HEAD")
  58. get = partialmethod(request, "GET")
  59. post = partialmethod(request, "POST")
  60. put = partialmethod(request, "PUT")
  61. patch = partialmethod(request, "PATCH")
  62. delete = partialmethod(request, "DELETE")