-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_client.py
More file actions
76 lines (69 loc) · 2.86 KB
/
http_client.py
File metadata and controls
76 lines (69 loc) · 2.86 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
75
76
from typing import Dict, Any, Union
import requests
from requests.exceptions import RequestException
class HttpClient:
def __init__(
self,
base_url: str = None,
timeout: int = 10,
headers: Dict[str, str] = None
):
self.base_url = base_url
self.timeout = timeout
self.session = requests.Session()
if headers:
self.session.headers.update(headers)
def get(self, path: str, params: Dict[str, Any] = None, headers: Dict[str, str] = None) -> Dict[str, Any]:
url = f"{self.base_url}{path}" if self.base_url else path
try:
response = self.session.get(url, params=params, headers=headers, timeout=self.timeout)
response.raise_for_status()
return response.json()
except RequestException as e:
return {
"success": False,
"error": str(e),
"status_code": e.response.status_code if hasattr(e, 'response') else 500
}
def post(
self,
path: str,
data: Union[Dict[str, Any], str] = None,
json: Dict[str, Any] = None,
headers: Dict[str, str] = None
) -> Dict[str, Any]:
url = f"{self.base_url}{path}" if self.base_url else path
try:
response = self.session.post(url, data=data, json=json, headers=headers, timeout=self.timeout)
response.raise_for_status()
return response.json()
except RequestException as e:
return {
"success": False,
"error": str(e),
"status_code": e.response.status_code if hasattr(e, 'response') else 500
}
def put(self, path: str, data: Dict[str, Any] = None, headers: Dict[str, str] = None) -> Dict[str, Any]:
url = f"{self.base_url}{path}" if self.base_url else path
try:
response = self.session.put(url, data=data, headers=headers, timeout=self.timeout)
response.raise_for_status()
return response.json()
except RequestException as e:
return {
"success": False,
"error": str(e),
"status_code": e.response.status_code if hasattr(e, 'response') else 500
}
def delete(self, path: str, headers: Dict[str, str] = None) -> Dict[str, Any]:
url = f"{self.base_url}{path}" if self.base_url else path
try:
response = self.session.delete(url, headers=headers, timeout=self.timeout)
response.raise_for_status()
return {"success": True, "status_code": response.status_code}
except RequestException as e:
return {
"success": False,
"error": str(e),
"status_code": e.response.status_code if hasattr(e, 'response') else 500
}