/
client.py
94 lines (76 loc) · 3.19 KB
/
client.py
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
84
85
86
87
88
89
90
91
92
93
94
import requests
import json
import consts as c
import utils
import exceptions
import logging
log_format = '%(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(filename='mylog-rest.json', filemode='a', format=log_format, level=logging.INFO)
# logging.warning('warn message')
# logging.info('info message')
# logging.debug('debug message')
# logging.error('error message')
# logging.critical('critical message')
class Client(object):
def __init__(self, api_key, api_seceret_key, passphrase, use_server_time=False):
self.API_KEY = api_key
self.API_SECRET_KEY = api_seceret_key
self.PASSPHRASE = passphrase
self.use_server_time = use_server_time
def _request(self, method, request_path, params, cursor=False):
if method == c.GET:
request_path = request_path + utils.parse_params_to_str(params)
# url
url = c.API_URL + request_path
timestamp = utils.get_timestamp()
# print(timestamp)
# sign & header
if self.use_server_time:
timestamp = self._get_timestamp()
# print(timestamp)
body = json.dumps(params) if method == c.POST else ""
sign = utils.sign(utils.pre_hash(timestamp, method, request_path, str(body)), self.API_SECRET_KEY)
# print(utils.pre_hash(timestamp, method, request_path, str(body)))
header = utils.get_header(self.API_KEY, sign, timestamp, self.PASSPHRASE)
# send request
response = None
# print("url:", url)
logging.info("url:" + url)
# print("headers:", header)
# print("body:", body)
logging.info("body:" + body)
if method == c.GET:
response = requests.get(url, headers=header)
elif method == c.POST:
response = requests.post(url, data=body, headers=header)
#response = requests.post(url, json=body, headers=header)
elif method == c.DELETE:
response = requests.delete(url, headers=header)
# exception handle
if not str(response.status_code).startswith('2'):
raise exceptions.OkexAPIException(response)
try:
res_header = response.headers
if cursor:
r = dict()
try:
r['before'] = res_header['OK-BEFORE']
r['after'] = res_header['OK-AFTER']
except:
print("")
return response.json(), r
else:
return response.json()
except ValueError:
raise exceptions.OkexRequestException('Invalid Response: %s' % response.text)
def _request_without_params(self, method, request_path):
return self._request(method, request_path, {})
def _request_with_params(self, method, request_path, params, cursor=False):
return self._request(method, request_path, params, cursor)
def _get_timestamp(self):
url = c.API_URL + c.SERVER_TIMESTAMP_URL
response = requests.get(url)
if response.status_code == 200:
return response.json()['iso']
else:
return ""