-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsteinapi.py
More file actions
58 lines (51 loc) · 2.09 KB
/
steinapi.py
File metadata and controls
58 lines (51 loc) · 2.09 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
58
import httpx
import logging
import time
class SteinAPI:
"""Holds the connection to THW stein.app"""
baseurl = "https://stein.app/api/api/ext"
def __init__(self, bu_id: int, api_key: str) -> None:
"""Initialize with the business unit ID and API key."""
self.bu_id = bu_id
self.session = httpx.Client(http2=True, headers={
'User-Agent': 'Mozilla/5.0',
'Accept': 'application/json',
'Authorization': f'Bearer {api_key}' # use Bearer token format
})
self.last_request_time = 0
self.assets = []
def _rate_limit(self):
"""Ensure we don't exceed the rate limit of 20 requests per minute."""
current_time = time.time()
elapsed_time = current_time - self.last_request_time
if elapsed_time < 3: # 60 seconds / 20 requests = 3 seconds per request
time.sleep(3 - elapsed_time)
self.last_request_time = time.time()
def get_assets(self) -> dict:
"""Fetch assets for the business unit."""
if len(self.assets) == 0:
self._rate_limit()
url = f"{self.baseurl}/assets/?buIds={self.bu_id}"
response = self.session.get(url)
response.raise_for_status()
self.assets = response.json()
return self.assets
def update_asset(self, asset_id: int, update_data: dict, notify: bool = False) -> bool:
"""Update an asset with the provided data."""
assetdata = None
for a in self.get_assets():
if a['id'] == asset_id:
assetdata = a
if "id" in update_data:
del update_data["id"]
# update old assetdata
assetdata.update(update_data)
self._rate_limit()
url = f"{self.baseurl}/assets/{asset_id}"
params = {'notifyRadio': str(notify).lower()}
response = self.session.patch(url, json=assetdata, params=params)
if response.status_code == 200:
return True
else:
logging.warning(f"Failed to update asset {asset_id}: {response.text}")
return False