Skip to content

Commit

Permalink
fix err and add auth header to client
Browse files Browse the repository at this point in the history
  • Loading branch information
Kraysent committed May 5, 2024
1 parent 4ee0f69 commit d1a7fa4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
21 changes: 18 additions & 3 deletions hyperleda/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,34 @@ class HyperLedaClient:
"""

# TODO: credentials
def __init__(self, endpoint: str = config.DEFAULT_ENDPOINT) -> None:
def __init__(self, endpoint: str = config.DEFAULT_ENDPOINT, token: str | None = None) -> None:
self.endpoint = endpoint
self.token = token

def _set_auth(self, headers: dict[str, str]) -> dict[str, str]:
if self.token is not None:
headers["Authorization"] = f"Bearer {self.token}"

return headers

def _post(self, path: str, request: Any) -> dict[str, Any]:
response = requests.post(f"{self.endpoint}{path}", json=dataclasses.asdict(request))
headers = {}
if path.startswith("/api/v1/admin"):
headers = self._set_auth(headers)

response = requests.post(f"{self.endpoint}{path}", json=dataclasses.asdict(request), headers=headers)

if not response.ok:
raise error.APIError.from_dict(response.json())

return response.json()

def _get(self, path: str, query: dict[str, str]) -> dict[str, Any]:
response = requests.get(f"{self.endpoint}{path}", params=query)
headers = {}
if path.startswith("/api/v1/admin"):
headers = self._set_auth(headers)

response = requests.get(f"{self.endpoint}{path}", params=query, headers=headers)

if not response.ok:
raise error.APIError.from_dict(response.json())
Expand Down
10 changes: 1 addition & 9 deletions hyperleda/error.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,4 @@
from dataclasses import dataclass


@dataclass
class APIError(Exception):
code: str
status: int
message: str

@classmethod
def from_dict(cls, data: dict) -> "APIError":
return APIError(**data)
return Exception(f"{data['code']} (code {data['status']}): {data['message']}")

0 comments on commit d1a7fa4

Please sign in to comment.