-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_client.py
More file actions
195 lines (171 loc) · 6.19 KB
/
api_client.py
File metadata and controls
195 lines (171 loc) · 6.19 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
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
#!/usr/bin/env python
from urllib.request import urlopen
from urllib.parse import quote_plus
import hmac
import json
import urllib.error
from functools import reduce
import sys
from enum import Enum
class Method(Enum):
GET = 'get'
PUT = 'put'
class Controller(Enum):
LOGS = 'LogsAPI'
BADGES = 'BadgesAPI'
USERS = 'UsersAPI'
class APIClient:
def __init__(self) -> None:
local_test = False
if local_test:
self.base_url = 'http://localhost:8080'
else:
self.base_url = 'https://timbreuse.sectioninformatique.ch'
@staticmethod
def load_key() -> str:
with open('.key.json', 'r') as file:
return json.load(file)['key']
def create_token(self, date, badge_id, inside) -> str:
text = f'{date}{badge_id}{inside}'.encode()
key = self.load_key().encode()
token_text = hmac.new(key, text, 'sha256').hexdigest()
return token_text
def create_url_n(self, controller:str, method:str, arg:str) -> str:
'''
>>> api_client = APIClient()
>>> api_client.create_url_n('Logs', 'put', '2/3/4')
'http://localhost:8080/Logs/put/2/3/4'
# 'https://timbreuse.sectioninformatique.net/Logs/put/2/3/4'
'''
# return f'{base_url}/{method}/{arg}'
return (f'{self.base_url}/{controller}/'
f'{method}/{arg}')
def send(self, url) -> tuple:
'''
wrap function of urllib.request.urlopen
'''
print('send', file=sys.stderr)
try:
html_file = urlopen(url)
return html_file, html_file.status
except urllib.error.HTTPError as e:
return None, str(e)
def send_log(self, date, badge_id, inside) -> tuple:
'''
>>> client_API = APIClient()
>>> file, code = client_API.send_log(*fake_info_stamping())
>>> type(file)
<class 'http.client.HTTPResponse'>
>>> code
201
'''
print('APIClient.send_log', file=sys.stderr)
arg = self.create_arg_args(date, badge_id, inside, self.create_token(
date, badge_id, inside)
)
url = self.create_url_n(Controller.LOGS.value, Method.PUT.value, arg)
print(url, file=sys.stderr)
return self.send(url)
def receive_logs(self, start_date) -> list[dict]:
'''
receive all logs since the date in parameter from the server
>>> api_client = APIClient()
>>> logs = api_client.receive_logs("2022-12-12 00:00:00")
'''
print('receive_logs', file=sys.stderr)
print(start_date, file=sys.stderr)
token = self.create_token_args(start_date)
arg = self.create_arg_args(start_date, token)
url = self.create_url_n(Controller.LOGS.value, Method.GET.value, arg)
print(url, file=sys.stderr)
html_file = self.send(url)[0]
return json.loads(html_file.readline())
def send_badge_and_user(self, badge_id:int, name:str, surname:str):
'''
>>> api_client = APIClient()
>>> file, code = api_client.send_badge_and_user(44, 'John', 'Malc')
>>> type(file)
<class 'http.client.HTTPResponse'>
>>> code
201
'''
print('APIClient.send_badge_and_user', file=sys.stderr)
arg = self.create_arg_args(badge_id, name, surname,
self.create_token_args(badge_id, name, surname))
url = self.create_url_n(Controller.BADGES.value, Method.PUT.value, arg)
print(url, file=sys.stderr)
return self.send(url)
def receive_users(self, start_date) -> list[dict]:
'''
receive all users from the server
>>> api_client = APIClient()
>>> users = api_client.receive_users('2023-02-03 00:00:00')
>>> isinstance(users, list)
True
'''
print('receive_users', file=sys.stderr)
token = self.create_token_args(start_date)
arg = self.create_arg_args(start_date, token)
url = self.create_url_n(Controller.USERS.value, Method.GET.value, arg)
print(url, file=sys.stderr)
html_file = self.send(url)[0]
return json.loads(html_file.readline())
def receive_badges(self, start_date):
'''
receive all badges from the server
>>> api_client = APIClient()
>>> badges = api_client.receive_badges('2023-02-03 00:00:00')
>>> isinstance(badges, list)
True
'''
print('receive_badges', file=sys.stderr)
print('start_date', start_date, file=sys.stderr)
token = self.create_token_args(start_date)
arg = self.create_arg_args(start_date, token)
url = self.create_url_n(Controller.BADGES.value, Method.GET.value, arg)
print(url, file=sys.stderr)
html_file = self.send(url)[0]
return json.loads(html_file.readline())
@staticmethod
def create_arg_args(*args) -> str:
'''
>>> APIClient.create_arg_args('a', 'b', 'c')
'a/b/c'
'''
print('create_arg_args', file=sys.stderr)
text = reduce(lambda cumulator, word:f'{cumulator}/{word}', args)
return quote_plus(text, '/')
@classmethod
def create_token_args(cls, *args) -> str:
'''
>>> badge_id, name, surname = 1, 'Sam', 'Smith'
>>> api_client = APIClient()
>>> api_client.create_token_args(badge_id, name, surname)
'1d0e1bc7fb9d9588833c427aa27b3d5edd20725cdee071e8c3f60d6009761e57'
'''
text = reduce(lambda cumulator,
word: f'{cumulator}{word}', args)
# is necessary args is one arg
text = str(text)
print(type(text), text, file=sys.stderr)
text = text.encode()
print(type(text), text, file=sys.stderr)
key = cls.load_key().encode()
token_text = hmac.new(key, text, 'sha256').hexdigest()
return token_text
def fake_info_stamping() -> tuple:
import datetime
date = datetime.datetime.now()
badge_id = 42
inside = 1
inside = 1 if bool(inside) else 0
return date, badge_id, inside
def main():
test = 0
if test == 0:
import doctest
doctest.testmod()
elif test == 1:
pass
if __name__ == "__main__":
main()