-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSessionClient.py
More file actions
56 lines (38 loc) · 1.67 KB
/
SessionClient.py
File metadata and controls
56 lines (38 loc) · 1.67 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
import requests
from exceptions import DexilonAPIException, DexilonRequestException, DexilonAuthException
class SessionClient:
def __init__(self, base_url: str, headers: dict = {}) -> None:
self.STATUS_CODES_TO_PROCESS = {200, 400, 401}
self.base_url: str = base_url
self.session: requests.Session = requests.Session()
self.session.headers.update(headers)
def update_headers(self, headers: dict = {}) -> None:
self.session.headers.update(headers)
def delete_header(self, header_name: str) -> None:
self.session.headers.pop(header_name)
def request(self, method: str, path: str, params: dict = None, data: dict = None) -> dict:
request = requests.Request(
method=method.upper(),
url=self.base_url + path,
params=params,
json=data
)
prepared_request = self.session.prepare_request(request)
response = self.session.send(request=prepared_request)
try:
data = response.json()
if response.status_code == 404 and 'code' in data:
return data
if not response.status_code in self.STATUS_CODES_TO_PROCESS:
errors = data.get('errors', {})
raise DexilonAPIException(
code=errors.get('code', [0])[0],
message=errors.get('message', [''])[0]
)
if response.status_code == 401:
raise DexilonAuthException(data)
return data
except ValueError:
raise DexilonRequestException(
message='Invalid Response: {}'.format(response.text)
)