-
Notifications
You must be signed in to change notification settings - Fork 12
/
client.py
74 lines (56 loc) · 2.37 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
import requests
import json
import consts as c, utils, exceptions
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):
request_path = request_path + utils.parse_params_to_str(params)
# url
url = c.API_URL + request_path
timestamp = utils.get_timestamp()
# sign & header
if self.use_server_time:
timestamp = self._get_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)
header = utils.get_header(self.API_KEY, sign, timestamp, self.PASSPHRASE)
# send request
response = None
if method == c.GET:
response = requests.get(url, headers=header)
elif method == c.POST:
response = requests.post(url, data=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 ""