Skip to content

Commit b443569

Browse files
authored
Merge pull request #8 from allenhaozi/feat/response
format response
2 parents d6f7120 + fbbfc1a commit b443569

File tree

6 files changed

+80
-12
lines changed

6 files changed

+80
-12
lines changed

src/bohrium/__init__.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
from ._client import Bohrium, AsyncBohrium
2-
from ._base_client import AsyncAPIClient, SyncAPIClient
2+
from ._base_client import AsyncAPIClient, SyncAPIClient, BaseClient
33
from ._utils._logs import setup_logging as _setup_logging
44

55
_setup_logging()
66

7-
__all__ = ["Bohrium", "AsyncBohrium", "AsyncAPIClient", "SyncAPIClient"]
7+
__all__ = [
8+
"Bohrium",
9+
"AsyncBohrium",
10+
"AsyncAPIClient",
11+
"SyncAPIClient",
12+
"BaseClient",
13+
]

src/bohrium/_base_client.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@
99
Generic,
1010
Literal,
1111
Mapping,
12+
Optional,
1213
TypeVar,
1314
Union,
1415
cast,
15-
Optional
1616
)
1717
from urllib.parse import urljoin
1818

@@ -114,7 +114,7 @@ class BaseClient(Generic[_HttpxClientT]):
114114
max_retries: int
115115
timeout: Union[float, Timeout, None]
116116
_limits: httpx.Limits
117-
_version: str | None
117+
_version: Union[str, None]
118118

119119
def __init__(
120120
self,
@@ -151,7 +151,7 @@ def _build_params(self, custom_params) -> dict[str, str]:
151151
return params
152152

153153
@property
154-
def custom_auth(self) -> httpx.Auth | None:
154+
def custom_auth(self) -> Union[httpx.Auth, None]:
155155
return None
156156

157157
@property
@@ -167,9 +167,7 @@ def default_headers(self) -> dict[str, str]:
167167

168168
@property
169169
def default_params(self) -> dict[str, str]:
170-
return {
171-
"accessKey": self.access_key
172-
}
170+
return {"accessKey": self.access_key}
173171

174172
def platform_headers(self) -> Dict[str, str]:
175173
return platform_headers(self._version)
@@ -187,7 +185,11 @@ def _request(
187185
merged_params = self._build_params(kwargs.get("params"))
188186
try:
189187
return self._client.request(
190-
method.upper(), url, json=json, headers=merged_headers, params=merged_params
188+
method.upper(),
189+
url,
190+
json=json,
191+
headers=merged_headers,
192+
params=merged_params,
191193
)
192194
except httpx.TransportError as e:
193195
logger.error(f"Transport error: {e}.")

src/bohrium/_client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ class Bohrium(SyncAPIClient):
1717

1818
# client options
1919
access_key: str
20-
project_id: str | None
20+
project_id: Union[str, None]
2121

2222
def __init__(
2323
self,

src/bohrium/_response.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import httpx
2+
from typing import Any, Optional, Dict
3+
4+
5+
class APIErrorResponse:
6+
def __init__(self, message: str, status_code: int):
7+
self.message = message
8+
self.status_code = status_code
9+
10+
def to_dict(self) -> Dict[str, Any]:
11+
return {"error": self.message, "status_code": self.status_code}
12+
13+
def __repr__(self) -> str:
14+
return f"<APIErrorResponse(status_code={self.status_code}, message='{self.message}')>"
15+
16+
17+
class APIResponse:
18+
def __init__(self, response: httpx.Response):
19+
self._response = response
20+
self.status_code = response.status_code
21+
self.headers = response.headers
22+
self._json = self._parse_json(response)
23+
24+
def _parse_json(self, response: httpx.Response) -> Optional[Any]:
25+
"""Parses the JSON content of the response."""
26+
try:
27+
return response.json()
28+
except ValueError:
29+
return APIErrorResponse("Invalid JSON response", response.status_code)
30+
31+
@property
32+
def json(self) -> Optional[Any]:
33+
"""Returns the JSON content of the response or an APIErrorResponse if parsing fails."""
34+
return self._json
35+
36+
def is_success(self) -> bool:
37+
"""Returns True if the response status code indicates success."""
38+
return 200 <= self.status_code < 300
39+
40+
def raise_for_status(self):
41+
"""Raises an HTTPError if the response status code indicates an error."""
42+
if not self.is_success():
43+
raise httpx.HTTPStatusError(
44+
f"HTTP Error {self.status_code} for url {self._response.url}",
45+
request=self._response.request,
46+
response=self._response,
47+
)
48+
49+
def __repr__(self) -> str:
50+
return (
51+
f"<APIResponse(status_code={self.status_code}, "
52+
f"headers={dict(self.headers)}, "
53+
f"json={self._json})>"
54+
)

src/bohrium/resources/job/job.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@
88
from typing import Optional
99

1010
from ..._resource import AsyncAPIResource, SyncAPIResource
11+
from ..._response import APIResponse
1112
from ...types.job.job import JobAddRequest
1213
from ..tiefblue.tiefblue import Tiefblue
1314

15+
1416
log = logging.getLogger(__name__)
1517

1618

@@ -19,8 +21,11 @@ class Job(SyncAPIResource):
1921
def detail(self, job_id):
2022
log.info(f"detail job {job_id}")
2123
response = self._client.get(f"/openapi/v1/job/{job_id}")
24+
25+
log.info(response.json())
2226
log.debug(response)
23-
return response.json().get("data")
27+
return APIResponse(response).json
28+
#return response.json().get("data")
2429

2530
def submit(
2631
self,

src/bohrium/resources/tiefblue/tiefblue.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import os
55
from tqdm import tqdm
66
import time
7+
from typing import Union
78
from ..._base_client import SyncAPIClient
89
from httpx import URL
910
from pprint import pprint
@@ -28,7 +29,7 @@ class Tiefblue:
2829

2930
def __init__(
3031
self,
31-
base_url: str | URL | None = None,
32+
base_url: Union[str, URL] = None,
3233
) -> None:
3334

3435
if base_url is None:

0 commit comments

Comments
 (0)