Repository navigation
Expand file tree
/
Copy pathAPI.py
More file actions
52 lines (43 loc) · 1.49 KB
/
Copy pathAPI.py
File metadata and controls
52 lines (43 loc) · 1.49 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
#!/usr/bin/env python3
from typing import Literal, Optional, Union
from requests import request
class API:
def __init__(self, endpoint: str, host: str = "bwapi"):
self.__endpoint = endpoint
if not self.__endpoint.endswith("/"):
self.__endpoint += "/"
self.__host = host
@property
def endpoint(self) -> str:
return self.__endpoint
@property
def host(self) -> str:
return self.__host
def request(
self,
method: Union[Literal["POST"], Literal["GET"]],
url: str,
data: Optional[Union[dict, bytes]] = None,
files=None,
timeout=(10, 30),
) -> tuple[bool, str, Optional[int], Optional[dict]]:
try:
kwargs = {}
if isinstance(data, dict):
kwargs["json"] = data
elif isinstance(data, bytes):
kwargs["data"] = data
elif data is not None:
return False, f"Unsupported data type: {type(data)}", None, None
if files:
kwargs["files"] = files
resp = request(
method,
f"{self.__endpoint}{url if not url.startswith('/') else url[1:]}",
timeout=timeout,
headers={"User-Agent": "bwapi", "Host": self.__host},
**kwargs,
)
except Exception as e:
return False, f"Request failed: {e}", None, None
return True, "ok", resp.status_code, resp.json()