fix bug
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import asdict, is_dataclass
|
||||
from typing import Any
|
||||
|
||||
@@ -41,7 +42,7 @@ class Client:
|
||||
self.account_type = account_type
|
||||
return self
|
||||
|
||||
def _request(self, method: str, path: str, body: Any = None) -> Any:
|
||||
def _request_bytes(self, method: str, path: str, body: Any = None) -> bytes:
|
||||
if is_dataclass(body):
|
||||
body = asdict(body)
|
||||
attempts = 2 if _is_idempotent(method, path) else 1
|
||||
@@ -56,30 +57,45 @@ class Client:
|
||||
assert response is not None
|
||||
if response.status_code >= 400:
|
||||
try:
|
||||
message = response.json().get("error", response.text)
|
||||
message = response.text
|
||||
except (ValueError, AttributeError):
|
||||
message = response.text.strip()
|
||||
raise APIError(response.status_code, str(message))
|
||||
if not response.content:
|
||||
return b""
|
||||
|
||||
return response.content
|
||||
|
||||
def _get_bytes(self, path: str) -> bytes:
|
||||
return self._request_bytes("GET", path)
|
||||
|
||||
def _post_bytes(self, path: str, body: Any = None) -> bytes:
|
||||
return self._request_bytes("POST", path, {} if body is None else body)
|
||||
|
||||
def _get_json(self, path: str) -> Any:
|
||||
content = self._get_bytes(path)
|
||||
return self._decode_json(path, content)
|
||||
|
||||
def _post_json(self, path: str, body: Any = None) -> Any:
|
||||
content = self._post_bytes(path, body)
|
||||
return self._decode_json(path, content)
|
||||
|
||||
@staticmethod
|
||||
def _decode_json(path: str, content: bytes) -> Any:
|
||||
if not content:
|
||||
return None
|
||||
try:
|
||||
return response.json()
|
||||
return json.loads(content)
|
||||
except ValueError as exc:
|
||||
raise ValueError(
|
||||
f"invalid JSON from {path}: {response.content[:512]!r}"
|
||||
f"invalid JSON from {path}: {content[:512]!r}"
|
||||
) from exc
|
||||
|
||||
def _get(self, path: str) -> Any:
|
||||
return self._request("GET", path)
|
||||
|
||||
def _post(self, path: str, body: Any = None) -> Any:
|
||||
return self._request("POST", path, {} if body is None else body)
|
||||
|
||||
def _get_field(self, path: str, key: str) -> Any:
|
||||
return self._get(path).get(key)
|
||||
return self._get_json(path).get(key)
|
||||
|
||||
def _post_field(self, path: str, body: Any, key: str) -> Any:
|
||||
result = self._post(path, body)
|
||||
result = self._post_json(path, body)
|
||||
if isinstance(result, dict) and result.get("error"):
|
||||
raise BusinessError(result["error"])
|
||||
return result.get(key, result) if key and isinstance(result, dict) else result
|
||||
|
||||
Reference in New Issue
Block a user