-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcli_client.py
More file actions
57 lines (46 loc) · 1.62 KB
/
cli_client.py
File metadata and controls
57 lines (46 loc) · 1.62 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
55
56
57
import base64
import logging
from typing import Dict, List, Optional, Union
import requests
from socketsecurity import USER_AGENT
from .exceptions import APIFailure
from .socket_config import SocketConfig
logger = logging.getLogger("socketdev")
class CliClient:
def __init__(self, config: SocketConfig):
self.config = config
self._encoded_key = self._encode_key(config.api_key)
@staticmethod
def _encode_key(token: str) -> str:
return base64.b64encode(f"{token}:".encode()).decode('ascii')
def request(
self,
path: str,
method: str = "GET",
headers: Optional[Dict] = None,
payload: Optional[Union[Dict, str]] = None,
files: Optional[List] = None,
base_url: Optional[str] = None
) -> requests.Response:
url = f"{base_url or self.config.api_url}/{path}"
default_headers = {
'Authorization': f"Basic {self._encoded_key}",
'User-Agent': USER_AGENT,
"accept": "application/json"
}
headers = headers or default_headers
try:
response = requests.request(
method=method.upper(),
url=url,
headers=headers,
data=payload,
files=files,
timeout=self.config.timeout,
verify=not self.config.allow_unverified_ssl
)
response.raise_for_status()
return response
except requests.exceptions.RequestException as e:
logger.error(f"API request failed: {str(e)}")
raise APIFailure(f"Request failed: {str(e)}")