-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_client.py
More file actions
74 lines (68 loc) · 3.14 KB
/
api_client.py
File metadata and controls
74 lines (68 loc) · 3.14 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import aiohttp
import requests
import logging
# Logger einrichten
logger = logging.getLogger("APIClientLogger")
logger.setLevel(logging.INFO)
handler = logging.FileHandler("api_client.log", encoding="utf-8")
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
class APIClient:
def __init__(self, base_url, token):
self.base_url = base_url.rstrip("/")
self.headers = {"Authorization": f"Bearer {token}"}
async def get(self, endpoint):
"""Sendet eine GET-Anfrage asynchron."""
url = f"{self.base_url}/{endpoint.lstrip('/')}"
try:
async with aiohttp.ClientSession(headers=self.headers) as session:
async with session.get(url) as response:
if response.status == 200:
return await response.text()
else:
logger.error(f"GET-Anfrage fehlgeschlagen: {url}, Status: {response.status}, Response: {await response.text()}")
return None
except Exception as e:
logger.error(f"Fehler bei GET-Anfrage: {url}, Fehler: {str(e)}")
return None
async def post(self, endpoint, data):
"""Sendet eine POST-Anfrage asynchron."""
url = f"{self.base_url}/{endpoint.lstrip('/')}"
try:
async with aiohttp.ClientSession(headers=self.headers) as session:
async with session.post(url, json=data) as response:
if response.status == 200:
return await response.json()
else:
logger.error(f"POST-Anfrage fehlgeschlagen: {url}, Status: {response.status}, Response: {await response.text()}")
return None
except Exception as e:
logger.error(f"Fehler bei POST-Anfrage: {url}, Fehler: {str(e)}")
return None
def sync_get(self, endpoint):
"""Sendet eine GET-Anfrage synchron."""
url = f"{self.base_url}/{endpoint.lstrip('/')}"
try:
response = requests.get(url, headers=self.headers)
if response.status_code == 200:
return response.text
else:
logger.error(f"Sync GET-Anfrage fehlgeschlagen: {url}, Status: {response.status_code}, Response: {response.text}")
return None
except Exception as e:
logger.error(f"Fehler bei Sync GET-Anfrage: {url}, Fehler: {str(e)}")
return None
def sync_post(self, endpoint, data):
"""Sendet eine POST-Anfrage synchron."""
url = f"{self.base_url}/{endpoint.lstrip('/')}"
try:
response = requests.post(url, json=data, headers=self.headers)
if response.status_code == 200:
return response.json()
else:
logger.error(f"Sync POST-Anfrage fehlgeschlagen: {url}, Status: {response.status_code}, Response: {response.text}")
return None
except Exception as e:
logger.error(f"Fehler bei Sync POST-Anfrage: {url}, Fehler: {str(e)}")
return None