This repository was archived by the owner on May 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
83 lines (68 loc) · 2.77 KB
/
client.py
File metadata and controls
83 lines (68 loc) · 2.77 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
77
78
79
80
81
82
83
import requests
from urllib.parse import urlencode
from .log import logger
class RestAPI:
def __init__(self, endpoint, api_token, user_agent, timeout=60):
self.endpoint = endpoint
self.timeout = timeout
self.headers = {
'Authorization': 'Bearer {}'.format(api_token),
'Content-type': 'application/json',
'User-Agent': user_agent,
}
def _return_result(self, r):
result = {
'status_code': r.status_code,
}
try:
result['data'] = r.json()
except ValueError:
result['data'] = None
return result
def _handle_payload(self, payload):
if not payload:
return
data = dict()
for k, v in payload.items():
if v is not None:
data[k] = v
return data
def get_resources(self, resource, payload=None, resource_id=None):
if not resource:
return {}
query_url = self.endpoint + '/' + resource
if resource_id:
query_url = query_url + '/' + resource_id
if payload:
for k, v in payload.items():
if v is not None:
data = urlencode({k: v})
else:
data = k
break
query_url = query_url + '?' + data
logger.debug("HTTP GET: {}".format(query_url))
r = requests.get(query_url, headers=self.headers, timeout=self.timeout)
return self._return_result(r)
def post_patch_resource(self, resource, payload=None, resource_id=None, action=None):
data = self._handle_payload(payload)
query_url = self.endpoint + '/' + resource
if not resource_id:
logger.debug("HTTP POST URL {}, data {}".format(query_url, data))
r = requests.post(query_url, json=data, headers=self.headers, timeout=self.timeout)
return self._return_result(r)
query_url += '/' + resource_id
if action:
query_url += '/' + action
logger.debug("HTTP POSTst URL {}, data {}".format(query_url, data))
r = requests.post(query_url, json=data, headers=self.headers, timeout=self.timeout)
return self._return_result(r)
else:
logger.debug("HTTP POST URL {}, data {}".format(query_url, data))
r = requests.patch(query_url, json=data, headers=self.headers, timeout=self.timeout)
return self._return_result(r)
def delete_resource(self, resource, resource_id):
query_url = self.endpoint + '/' + resource + '/' + resource_id
logger.debug("HTTP DELETE: {}".format(query_url))
r = requests.delete(query_url, headers=self.headers, timeout=self.timeout)
return self._return_result(r)