-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
54 lines (42 loc) · 1.78 KB
/
client.py
File metadata and controls
54 lines (42 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import os
import httpx
from pydantic import BaseModel
from typing import Optional, Any
from functools import partial
from .resources.exceptions.exceptions import AuthenticationError
class APIHttpClient:
def __init__(self, base_url: str = "https://codesphere.com/api"):
auth_token = os.environ.get("CS_TOKEN")
if not auth_token:
raise AuthenticationError()
self._token = auth_token
self._base_url = base_url
self.client: Optional[httpx.AsyncClient] = None
# Dynamically create get, post, put, patch, delete methods
for method in ["get", "post", "put", "patch", "delete"]:
setattr(self, method, partial(self.request, method.upper()))
async def __aenter__(self):
timeout_config = httpx.Timeout(10.0, read=30.0)
self.client = httpx.AsyncClient(
base_url=self._base_url,
headers={"Authorization": f"Bearer {self._token}"},
timeout=timeout_config,
)
return self
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any):
if self.client:
await self.client.aclose()
async def request(
self, method: str, endpoint: str, **kwargs: Any
) -> httpx.Response:
if not self.client:
raise RuntimeError(
"APIHttpClient must be used within an 'async with' statement."
)
# If a 'json' payload is a Pydantic model, automatically convert it.
if "json" in kwargs and isinstance(kwargs["json"], BaseModel):
kwargs["json"] = kwargs["json"].model_dump(exclude_none=True)
print(f"{method} {endpoint} {kwargs}")
response = await self.client.request(method, endpoint, **kwargs)
response.raise_for_status()
return response