2023-09-25 22:52:29 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2023-10-07 08:17:43 +00:00
|
|
|
import json
|
2023-11-19 04:36:04 +00:00
|
|
|
from contextlib import asynccontextmanager
|
2023-10-02 00:04:22 +00:00
|
|
|
from functools import partialmethod
|
2023-11-19 04:36:04 +00:00
|
|
|
from typing import AsyncGenerator
|
2023-09-25 22:52:29 +00:00
|
|
|
|
2023-10-02 00:04:22 +00:00
|
|
|
from curl_cffi.requests import AsyncSession, Response
|
2023-09-25 22:52:29 +00:00
|
|
|
|
|
|
|
class StreamResponse:
|
2023-11-19 04:36:04 +00:00
|
|
|
def __init__(self, inner: Response) -> None:
|
2023-10-07 08:17:43 +00:00
|
|
|
self.inner: Response = inner
|
2023-10-02 00:04:22 +00:00
|
|
|
self.request = inner.request
|
2023-10-07 08:17:43 +00:00
|
|
|
self.status_code: int = inner.status_code
|
|
|
|
self.reason: str = inner.reason
|
|
|
|
self.ok: bool = inner.ok
|
2023-09-26 08:03:37 +00:00
|
|
|
self.headers = inner.headers
|
|
|
|
self.cookies = inner.cookies
|
2023-09-25 22:52:29 +00:00
|
|
|
|
|
|
|
async def text(self) -> str:
|
2023-11-19 04:36:04 +00:00
|
|
|
return await self.inner.atext()
|
2023-09-25 22:52:29 +00:00
|
|
|
|
2023-10-07 08:17:43 +00:00
|
|
|
def raise_for_status(self) -> None:
|
2023-11-19 04:36:04 +00:00
|
|
|
self.inner.raise_for_status()
|
2023-09-25 22:52:29 +00:00
|
|
|
|
2023-10-07 08:17:43 +00:00
|
|
|
async def json(self, **kwargs) -> dict:
|
2023-11-19 04:36:04 +00:00
|
|
|
return json.loads(await self.inner.acontent(), **kwargs)
|
2023-10-02 00:04:22 +00:00
|
|
|
|
2023-11-19 04:36:04 +00:00
|
|
|
async def iter_lines(self) -> AsyncGenerator[bytes, None]:
|
|
|
|
async for line in self.inner.aiter_lines():
|
|
|
|
yield line
|
2023-10-02 00:04:22 +00:00
|
|
|
|
2023-11-19 04:36:04 +00:00
|
|
|
async def iter_content(self) -> AsyncGenerator[bytes, None]:
|
|
|
|
async for chunk in self.inner.aiter_content():
|
2023-10-02 00:04:22 +00:00
|
|
|
yield chunk
|
|
|
|
|
|
|
|
class StreamSession(AsyncSession):
|
2023-11-19 04:36:04 +00:00
|
|
|
@asynccontextmanager
|
|
|
|
async def request(
|
2023-10-07 17:00:45 +00:00
|
|
|
self, method: str, url: str, **kwargs
|
2023-11-19 04:36:04 +00:00
|
|
|
) -> AsyncGenerator[StreamResponse]:
|
|
|
|
response = await super().request(method, url, stream=True, **kwargs)
|
|
|
|
try:
|
|
|
|
yield StreamResponse(response)
|
|
|
|
finally:
|
|
|
|
await response.aclose()
|
2023-10-07 08:17:43 +00:00
|
|
|
|
2023-09-26 08:03:37 +00:00
|
|
|
head = partialmethod(request, "HEAD")
|
|
|
|
get = partialmethod(request, "GET")
|
|
|
|
post = partialmethod(request, "POST")
|
|
|
|
put = partialmethod(request, "PUT")
|
|
|
|
patch = partialmethod(request, "PATCH")
|
|
|
|
delete = partialmethod(request, "DELETE")
|