-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathexample.py
executable file
·173 lines (144 loc) · 5.08 KB
/
example.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/usr/bin/python3
import asyncio
import aiohttp
import time
import json
import logging
import argparse
import msgpack
import qpack
class Auth:
def __init__(self, secret, url, only_secret=False):
self.url = url
self._secret = secret
self._token = None
self._refresh_ts = None
self._refresh_token = None
self._only_secret = only_secret
async def get_header(self, content_type='application/json'):
if not self._secret:
return {
'Content-Type': content_type
}
if self._only_secret:
return {
'Authorization': 'Secret {}'.format(self._secret),
'Content-Type': content_type
}
if self._token is None:
await self._get_token()
elif time.time() > self._refresh_ts:
await self._refresh()
return {
'Authorization': 'Token {}'.format(self._token),
'Content-Type': content_type
}
def _update(self, content):
self._refresh_token = content['refresh_token']
self._refresh_ts = \
int(time.time()) + content['expires_in'] // 2
self._token = content['token']
async def _get_token(self):
headers = {
'Authorization': 'Secret {}'.format(self._secret),
'Content-Type': 'application/json'
}
async with aiohttp.ClientSession() as session:
async with session.post(
'{}/get-token'.format(self.url),
headers=headers) as resp:
if resp.status == 200:
self._update(await resp.json())
else:
logging.error('Error getting token: {}'.format(resp.status))
async def _refresh(self):
headers = {
'Authorization': 'Refresh {}'.format(self._refresh_token),
'Content-Type': 'application/json'
}
async with aiohttp.ClientSession() as session:
async with session.post(
'{}/refresh-token'.format(self.url),
headers=headers) as resp:
if resp.status == 200:
self._update(await resp.json())
else:
logging.error(
'Error getting token: {}'
.format(resp.status))
async def _query(auth, data, headers):
async with aiohttp.ClientSession() as session:
async with session.post(
'{}/query'.format(auth.url),
data=data,
headers=headers) as resp:
status = resp.status
res = await resp.read()
return res, status
async def query_json(auth, q):
data = {'query': q}
headers = await auth.get_header()
res, status = await _query(auth, json.dumps(data), headers)
return json.loads(res.decode('utf-8')), status
async def query_csv(auth, q):
data = '"query","{}"'.format(q.replace('"', '""'))
headers = await auth.get_header(content_type='application/csv')
res, status = await _query(auth, data, headers)
return res.decode('utf-8'), status
async def query_msgpack(auth, q):
data = {'query': q}
headers = await auth.get_header(content_type='application/x-msgpack')
res, status = await _query(auth, msgpack.packb(data), headers)
return msgpack.unpackb(res, encoding='utf-8'), status
async def query_qpack(auth, q):
data = {'query': q}
headers = await auth.get_header(content_type='application/x-qpack')
res, status = await _query(auth, qpack.packb(data), headers)
return qpack.unpackb(res, decode='utf-8'), status
async def example_show(args, auth, method='json'):
methods = {
'json': query_json,
'msgpack': query_msgpack,
'qpack': query_qpack
}
res, status = await methods[method](auth, 'show')
if status == 200:
for item in res['data']:
print('{name:.<20}: {value}'.format(**item))
else:
print('Error: {}'.format(res.get('error_msg', status)))
async def example_query(args, auth):
res, status = await query_csv(auth, args.query)
print(res)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'-u',
'--url',
type=str,
default='http://localhost:8080',
help='SiriDB HTTP url')
parser.add_argument(
'-s',
'--secret',
type=str,
default='',
help='Authenticate using a secret')
parser.add_argument(
'-o', '--only-secret',
action='store_true',
help='Only authenticate using the secret. ' +
'(can only be used if a token is not required)')
parser.add_argument(
'-q',
'--query',
type=str,
default='',
help='Send a query, output is parsed as csv')
args = parser.parse_args()
loop = asyncio.get_event_loop()
auth = Auth(args.secret, args.url, args.only_secret)
if args.query:
loop.run_until_complete(example_query(args, auth))
else:
loop.run_until_complete(example_show(args, auth))