2022-10-08 00:59:08 +00:00
|
|
|
from contextlib import AbstractAsyncContextManager
|
|
|
|
from types import TracebackType
|
|
|
|
from typing import Optional, Type
|
|
|
|
|
|
|
|
import httpx
|
|
|
|
|
2022-12-10 12:37:43 +00:00
|
|
|
__all__ = ("HTTPXRequest",)
|
|
|
|
|
2023-04-25 15:00:44 +00:00
|
|
|
from core.config import config
|
|
|
|
|
|
|
|
timeout = httpx.Timeout(
|
|
|
|
timeout=config.timeout,
|
|
|
|
read=config.read_timeout,
|
|
|
|
write=config.write_timeout,
|
|
|
|
connect=config.connect_timeout,
|
|
|
|
pool=config.pool_timeout,
|
|
|
|
)
|
|
|
|
|
2022-10-08 00:59:08 +00:00
|
|
|
|
|
|
|
class HTTPXRequest(AbstractAsyncContextManager):
|
|
|
|
def __init__(self, *args, headers=None, **kwargs):
|
2023-04-26 08:48:05 +00:00
|
|
|
self._client = httpx.AsyncClient(headers=headers, *args, **kwargs)
|
2022-10-08 00:59:08 +00:00
|
|
|
|
|
|
|
async def __aenter__(self):
|
|
|
|
try:
|
|
|
|
await self.initialize()
|
|
|
|
return self
|
|
|
|
except Exception as exc:
|
|
|
|
await self.shutdown()
|
|
|
|
raise exc
|
|
|
|
|
2022-10-10 11:07:28 +00:00
|
|
|
async def __aexit__(
|
|
|
|
self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]
|
|
|
|
) -> None:
|
2022-10-08 00:59:08 +00:00
|
|
|
await self.initialize()
|
|
|
|
|
|
|
|
async def initialize(self):
|
|
|
|
if self._client.is_closed:
|
2023-04-25 15:00:44 +00:00
|
|
|
self._client = httpx.AsyncClient(timeout=timeout)
|
2022-10-08 00:59:08 +00:00
|
|
|
|
|
|
|
async def shutdown(self):
|
|
|
|
if self._client.is_closed:
|
|
|
|
return
|
|
|
|
await self._client.aclose()
|