-
Notifications
You must be signed in to change notification settings - Fork 1
/
AsyncioServer(1.b1).py
552 lines (512 loc) · 25.6 KB
/
AsyncioServer(1.b1).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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
import asyncio
import sys
from socket import AF_INET
import logging
from weakref import WeakKeyDictionary
from itertools import chain, product
import time
try:
from aiosqlite import connect, DatabaseError, ProgrammingError,\
OperationalError, NotSupportedError
from AIOEncryption import AsyncioBlockingIO
except ImportError as exc:
print(exc)
time.sleep(20)
class MyServer:
"""My example of asyncio TCP server,
with some db functionality,
using Python 3.9.1
writen in EAFP and code style
Мой пример Асинхронного TCP сервера
с запросами в БД, используется python 3.9.1
в EAFP стиле
"""
def __init__(self):
# this keep tracking all client tasks inside
self.clients = WeakKeyDictionary()
async def iterate_(self, data):
try:
s = chain(*product(data, '#'))
s = map(str, chain.from_iterable(s))
s = '^'.join((*s,))
except AttributeError:
log.error("Exception occurred", exc_info=True)
raise
else:
return s
async def enter(self, db, SQLlist):
try:
cursor = await db.execute("SELECT Password \
FROM Cipher \
WHERE Login = :Login",
{'Login': SQLlist[1]})
cursor = await cursor.fetchone()
if cursor:
check_ = (await asyncio.wait_for(\
AsyncioBlockingIO().check_pass(SQLlist[2], cursor[0]), timeout=2.0))
if check_:
cursor = await db.execute("SELECT employee_FIO \
FROM Cipher \
WHERE Login = :Login",
{'Login': SQLlist[1]})
cursor = await cursor.fetchone()
log.info(f"Сотрудник {SQLlist[1]} авторизировался")
cursor = "^".join(["GO", cursor[0]])
else:
log.info("Попытка входа с неправильным паролем")
cursor = "Fail"
else:
cursor = "NOLOG"
except (AttributeError, IndexError,\
OperationalError, ProgrammingError):
log.error("Exception occurred", exc_info=True)
raise
else:
return cursor
async def register(self, db, SQLlist):
try:
new_hash = (await asyncio.wait_for(\
AsyncioBlockingIO().to_hash_password(SQLlist[3]), timeout=2.0))
await db.execute("INSERT INTO Cipher (ID, Login, Password, employee_FIO)\
VALUES (:ID, :Login, :Password, :employee_FIO)",
{'ID': SQLlist[1], 'Login': SQLlist[2],
'Password': new_hash, 'employee_FIO': SQLlist[4]})
await db.commit()
log.info(f"Сотрудник {SQLlist[4]} зарегистрирован")
except (AttributeError, IndexError,\
OperationalError, ProgrammingError):
log.error("Exception occurred", exc_info=True)
raise
else:
msg = 'Reg'
return msg
async def changeuser(self, db, SQLlist):
try:
new_hash = (await asyncio.wait_for(\
AsyncioBlockingIO().to_hash_password(SQLlist[3]), timeout=2.0))
await db.execute("UPDATE Cipher \
SET Login = :Login, Password = :Password,\
employee_FIO = :employee_FIO \
WHERE ID = :ID",
{'ID': SQLlist[1], 'Login': SQLlist[2],
'Password': new_hash, 'employee_FIO': SQLlist[4]})
await db.commit()
except (AttributeError, IndexError,\
OperationalError, ProgrammingError):
log.error("Exception occured", exc_info=True)
raise
else:
log.info(f"Сотрудник {SQLlist[2]} изменён")
msg = "OK"
return msg
async def deleteuser(self, db, SQLlist):
try:
await db.execute("DELETE FROM Cipher\
WHERE ID = :ID",
{'ID': SQLlist[1]})
await db.commit()
except (AttributeError, IndexError,\
OperationalError, ProgrammingError):
log.error("Exception occurred", exc_info=True)
raise
else:
log.info(f"Сотрудник {SQLlist[1]} удален из БД")
msg = "OK"
return msg
async def allquery(self, db):
try:
cursor = await db.execute("SELECT rec_date, FIO, address,\
telephone, reason, current_tariff, realization_time,\
for_master, master, record_state,\
category, employee_FIO, reg_date, ID\
FROM records")
cursor = await cursor.fetchall()
cursor = await self.iterate_(cursor)
except (AttributeError, DatabaseError,\
OperationalError, ProgrammingError):
log.error("Exception occurred", exc_info=True)
raise
else:
log.info("Запрос на все заявки")
return cursor
async def userquery(self, db):
try:
cursor = await db.execute("SELECT ID, Login,\
Password, employee_FIO \
FROM Cipher")
cursor = await cursor.fetchall()
cursor = await self.iterate_(cursor)
except (AttributeError, DatabaseError,\
OperationalError, ProgrammingError):
log.error("Exception occurred", exc_info=True)
raise
else:
log.info("Запрос на информацию о сотрудниках")
return cursor
async def curquery(self, db, SQLlist):
try:
cursor = await db.execute("SELECT rec_date, FIO, address, telephone,\
reason, current_tariff, realization_time,\
for_master, master, record_state, category,\
employee_FIO, reg_date, ID\
FROM records \
WHERE rec_date = :rec_date",
{'rec_date': SQLlist[1]})
cursor = await cursor.fetchall()
if cursor == []:
print("На текущий день ничего нет")
cursor = 'No'
else:
log.info("Запрос на текущие заявки")
cursor = await self.iterate_(cursor)
except (AttributeError, IndexError,\
OperationalError, ProgrammingError):
log.error("Exception occurred", exc_info=True)
raise
else:
return cursor
async def insert(self, db, SQLlist):
try:
await db.execute("INSERT INTO records (category, FIO, address, telephone,\
reason, current_tariff, realization_time, for_master, master,\
rec_date, record_state, reg_date, employee_FIO)\
VALUES (:category, :FIO, :address, :telephone, :reason,\
:current_tariff, :realization_time, :for_master, :master, :rec_date,\
:record_state, :reg_date, :employee_FIO)",\
{
'category': SQLlist[1],
'FIO': SQLlist[2],
'address': SQLlist[3],
'telephone': SQLlist[4],
'reason': SQLlist[5],
'current_tariff': SQLlist[6],
'realization_time': SQLlist[7],
'for_master': SQLlist[8],
'master': SQLlist[9],
'rec_date': SQLlist[10],
'record_state': SQLlist[11],
'reg_date': SQLlist[12],
'employee_FIO': SQLlist[13]
})
await db.commit()
except (AttributeError, IndexError,\
OperationalError, ProgrammingError):
log.error("Exception occurred", exc_info=True)
raise
else:
log.info(f"Новая заявка добавлена в БД")
msg = "Новая запись добавлена"
return msg
async def delete(self, db, SQLlist):
try:
await db.execute("DELETE FROM records\
WHERE ID = :ID",
{'ID': SQLlist[1]})
await db.commit()
except (AttributeError, IndexError,\
OperationalError, ProgrammingError):
log.error("Exception occurred", exc_info=True)
raise
else:
log.info("Запрос на удаление заявки выполнен")
msg = 'Запись удалена'
return msg
async def update(self, db, SQLlist):
try:
await db.execute("UPDATE records\
SET category = :category, FIO = :FIO, address = :address,\
telephone = :telephone, reason = :reason, realization_time = :realization_time,\
for_master = :for_master, master = :master, record_state = :record_state,\
rec_date = :rec_date, current_tariff = :current_tariff\
WHERE ID = :ID",
{
'ID': SQLlist[1],
'category': SQLlist[2],
'FIO': SQLlist[3],
'address': SQLlist[4],
'telephone': SQLlist[5],
'reason': SQLlist[6],
'realization_time': SQLlist[7],
'for_master': SQLlist[8],
'master': SQLlist[9],
'record_state': SQLlist[10],
'rec_date': SQLlist[11],
'current_tariff': SQLlist[12]
})
await db.commit()
except (AttributeError, IndexError,\
OperationalError, ProgrammingError):
log.error("Exception occurred", exc_info=True)
raise
else:
log.info("Запрос на обновление заявки выполнен")
msg = "Запись обновлена"
return msg
async def access_db(self, SQLlist=list()):
"""This coroutine is used for DB connection
required data is defines via keyword from client
Эта корутина предназначена для соединения с БД
запрашиваемые данные определяются с помощью
ключевого слова, которое посылает клиент
"""
try:
keyword = SQLlist[0]
except IndexError:
log.error("Exception occurred", exc_info=True)
raise
else:
try:
async with connect("address_book.db") as db:
if keyword == "ENTER":
enter_ = await asyncio.shield(\
asyncio.wait_for(\
self.enter(db, SQLlist), timeout=2.0))
return enter_
elif keyword == "REGISTER":
register_ = await asyncio.shield(\
asyncio.wait_for(\
self.register(db, SQLlist), timeout=2.0))
return register_
elif keyword == "DELETEUSER":
delete_user_ = await asyncio.shield(\
asyncio.wait_for(\
self.deleteuser(db, SQLlist), timeout=2.0))
return delete_user_
elif keyword == "ALLQUERY":
all_query_ = await asyncio.shield(\
asyncio.wait_for(\
self.allquery(db), timeout=2.0))
return all_query_
elif keyword == "USERQUERY":
user_query_ = await asyncio.shield(\
asyncio.wait_for(\
self.userquery(db), timeout=2.0))
return user_query_
elif keyword == "CURQUERY":
cur_query_ = await asyncio.shield(\
asyncio.wait_for(\
self.curquery(db, SQLlist), timeout=2.0))
return cur_query_
elif keyword == "INSERT":
insert_ = await asyncio.shield(\
asyncio.wait_for(\
self.insert(db, SQLlist), timeout=2.0))
return insert_
elif keyword == "DELETE":
delete_ = await asyncio.shield(\
asyncio.wait_for(\
self.delete(db, SQLlist), timeout=2.0))
return delete_
elif keyword == "UPDATE":
update_ = await asyncio.shield(\
asyncio.wait_for(\
self.update(db, SQLlist), timeout=2.0))
return update_
elif keyword == "CHANGEUSER":
update_user = await asyncio.shield(\
asyncio.wait_for(\
self.changeuser(db, SQLlist), timeout=2.0))
return update_user
else:
log.info("Поступил неправильный запрос")
wrong_query = "Неправильный запрос"
return wrong_query
except (NotSupportedError, DatabaseError,\
asyncio.TimeoutError, asyncio.CancelledError):
log.error("Exception occured", exc_info=True)
raise
# when hadle_client Task in done state, closing connection
# and deleting connection from connections list
async def client_done(self, task, client_writer):
try:
del self.clients[task]
print("client task done", file = sys.stderr)
client_writer.close()
await client_writer.wait_closed()
except (IOError, Exception):
log.error("Exception occurred", exc_info=True)
raise
else:
return
async def accept_client(self, client_reader, client_writer):
"""This coroutine is used to accept client connection
Эта корутина используется для обработки соединений
от TCP клиента
"""
# start a new Task to handle this specific client connection
try:
handle_task = asyncio.create_task(\
self.handle_client(client_reader, client_writer))
except (asyncio.TimeoutError, asyncio.CancelledError,\
asyncio.IncompleteReadError, asyncio.InvalidStateError):
log.error("Exception occurred", exc_info=True)
raise
else:
try:
self.clients[handle_task] = client_reader, client_writer
done, pending = await asyncio.shield(\
asyncio.wait({handle_task}))
except (asyncio.TimeoutError, asyncio.CancelledError):
log.error("Exception occurred", exc_info=True)
handle_task.cancel()
raise
else:
if handle_task in done:
handle_task.cancel()
try:
done_task = asyncio.create_task(\
self.client_done(handle_task, client_writer))
done, pending = await asyncio.shield(\
asyncio.wait({done_task}))
except (asyncio.TimeoutError, asyncio.CancelledError,
asyncio.InvalidStateError):
log.error("Exception occurred", exc_info=True)
done_task.cancel()
raise
else:
if done_task in done:
done_task.cancel()
async def handle_client(self, client_reader, client_writer):
"""handles incoming TCP connection from client
обрабатывает запрос клиента
"""
while True:
# client_reader waits to reads data till EOF '\n'
try:
read_data_task = asyncio.create_task(client_reader.readline())
except (asyncio.TimeoutError, asyncio.IncompleteReadError,\
asyncio.InvalidStateError):
log.error("Exception occured", exc_info=True)
raise
else:
# if connection established
if read_data_task:
done, pending = await asyncio.shield(\
asyncio.wait({read_data_task}))
if read_data_task in done:
try:
received_query = read_data_task.result()
# this Task decrypts client message
decrypt_data_task = asyncio.create_task(\
AsyncioBlockingIO().decrypt_message(received_query))
done, pending = await asyncio.shield(\
asyncio.wait({decrypt_data_task}))
except (asyncio.InvalidStateError, asyncio.TimeoutError,\
asyncio.CancelledError):
log.error("Exception occurred", exc_info=True)
decrypt_data_task.cancel()
raise
else:
if decrypt_data_task in done:
try:
decrypted_data = decrypt_data_task.result()
message = decrypted_data.split("^")
addr = client_writer.get_extra_info('peername')
print(f"Connected to {addr!r}")
log.info(f"Connected to {addr!r}")
db_task = asyncio.create_task(self.access_db(SQLlist=message))
done, pending = await asyncio.shield(\
asyncio.wait({db_task}))
except (asyncio.TimeoutError, asyncio.CancelledError,\
asyncio.InvalidStateError):
log.error("Exception occurred", exc_info=True)
db_task.cancel()
raise
else:
if db_task in done:
try:
data_from_db = db_task.result()
# wait untill writer is ready
write_task = asyncio.create_task(\
self.write_response(client_writer, data_from_db))
done, pending = await asyncio.shield(\
asyncio.wait({write_task}))
except (asyncio.TimeoutError, asyncio.CancelledError,\
asyncio.InvalidStateError):
log.error("Exception occurred", exc_info=True)
write_task.cancel()
raise
finally:
# when write Task is done, .cancel all Tasks
if write_task in done:
try:
print("Connection finished")
return
except (asyncio.TimeoutError, asyncio.CancelledError,\
asyncio.InvalidStateError):
log.error("Exception occurred", exc_info=True)
raise
else:
break
async def write_response(self, client_writer, data):
"""This function encrypting data from DB query
and sends it to our client
Эта функция зашифровывает данные из БД
и отправляет их клиенту
"""
# Encrypts a new message and calculate it's length to send
try:
encrypt_task = asyncio.create_task(\
AsyncioBlockingIO().encrypt_message(data))
done, pending = await asyncio.shield(\
asyncio.wait({encrypt_task}))
except (asyncio.TimeoutError, asyncio.CancelledError,\
asyncio.InvalidStateError):
log.error("Exception occurred", exc_info=True)
raise
else:
if encrypt_task in done:
try:
query = encrypt_task.result()
except Exception:
log.error("Exception occurred", exc_info=True)
raise
else:
try:
client_writer.write(query)
except (asyncio.SendfileNotAvailableError, IOError):
log.error("Exception occured", exc_info=True)
raise
else:
await client_writer.drain()
async def start(self):
"""This coroutine starts our async TCP server
in event loop, reader and writer is passed to
coroutine accept_client, that responsible for
creating 'client connections' tasks in our server
that handles incoming connections
Эта корутина запускает наш асинхронный сервер
в петле событий, reader и writer передаются
корутине accept_client, которая ответственна
за создание задания на соединение между сервером и клиентом
"""
self.server = await asyncio.start_server(self.accept_client,\
host='172.20.20.14', port=43333,\
family=AF_INET,\
backlog=20, reuse_address=True)
addr = self.server.sockets[0].getsockname()
log.info(f'Serving on {addr!r}')
print(f'Serving on {addr!r}')
async with self.server:
await self.server.serve_forever()
if __name__ == "__main__":
try:
Server = MyServer()
log = logging.getLogger('asyncio')
f_format = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
log.setLevel(logging.INFO)
f_handler = logging.FileHandler('ServerLog.log')
f_handler.setFormatter(f_format)
log.addHandler(f_handler)
except Exception as exc:
print(exc)
time.sleep(20)
else:
try:
# Starting our server and loop with debug mode
asyncio.run(Server.start(), debug=True)
loop = asyncio.get_running_loop()
if loop.get_debug():
log.debug("Some exception")
except KeyboardInterrupt:
pass