-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync.py
More file actions
123 lines (90 loc) · 4.09 KB
/
Copy pathasync.py
File metadata and controls
123 lines (90 loc) · 4.09 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
### Эмуляция синхронных запросов по REST API к серверу
from typing import List
import random
import time
import uuid
import os
from pathlib import Path
from RandomWordGenerator import RandomWord
import asyncio
import concurrent.futures as pool
from concurrent.futures import ProcessPoolExecutor
# ProcessPoolExecuter
executor = ProcessPoolExecutor()
PATH_TO_DIR = "./result_files"
TIMES_WAIT: List[float] = [
0.9,
0.73,
0.1,
0.4,
1,
0.234,
0.53,
0.92,
0.45,
0.78,
]
async def send_request(id_request: uuid.UUID, time_wait: float) -> str:
""" Эмуляция отправки запроса на сервер """
print(f"[{id_request}] Отправил запрос и ожидаю ответа ...")
await asyncio.sleep(time_wait)
print(f"[{id_request}] Получил ответ")
print(f"[{id_request}] Время ожидания составило: {time_wait}")
return str(random.randint(1_000_000, 3_000_000))
async def parse_response(id_request: uuid.UUID, response: str, time_wait: float) -> int:
""" Эмуляция парсинга ответа от сервера """
if not isinstance(response, str):
raise ValueError("Некорректный тип данных ответа от сервера!")
print(f"[{id_request}] Парсинг ответа от сервера ...")
await asyncio.sleep(time_wait)
try:
responce: int = int(float(response))
return responce
except ValueError:
print(f"[{id_request}] Строка содержит некорректные символы!")
print(f"[{id_request}] Завершение ...")
exit(0)
except Exception as e:
print(f"[{id_request}] Непредвиденная ошибка: ", e)
print(f"[{id_request}] Завершение ...")
exit(0)
def output_responce(id_request: uuid.UUID, path_to_file: str) -> None:
""" Вывод пользователю уведомления об окончании обработки запроса """
output = f"""
Успешное выполнение запроса --> {id_request} !
Результирующий файл сгенерирован по пути: {path_to_file}
"""
print(output)
def generate_file(id_request: uuid.UUID, count_word: int) -> str:
""" Генерация файла рандомного содержания с заданным количеством слов """
rw = RandomWord(constant_word_size=False)
path_to_file: str = os.path.join(PATH_TO_DIR, f"random_words_file_{id_request}.txt")
with open(path_to_file, "w") as file:
[file.write(rw.generate() + "\n") for _ in range(count_word)]
return path_to_file
async def process_request(time_wait: float):
""" Эмуляция обработки запроса к серверу """
# Создает уникальный идентификатор эмулируемого запроса
id_request: uuid.UUID = uuid.uuid4()
responce: str = await send_request(id_request, time_wait)
count_word: int = await parse_response(id_request, responce, time_wait)
loop = asyncio.get_event_loop()
path_to_file: str = await loop.run_in_executor(executor, generate_file, id_request, count_word)
await loop.run_in_executor(executor, output_responce, id_request, path_to_file)
"""
responce: str = send_request(id_request, time_wait)
count_word: int = parse_response(id_request, responce, time_wait)
path_to_file: str = generate_file(id_request, count_word)
output_responce(id_request, path_to_file)"""
async def get_async():
start = time.time()
# Создает папку, если ее не существует
Path(PATH_TO_DIR).mkdir(exist_ok=True)
list_result = []
for time_wait in TIMES_WAIT:
process = asyncio.create_task(process_request(time_wait))
list_result.append(process)
await asyncio.gather(*list_result)
print("Общее время выполнение :", time.time() - start)
if __name__ == "__main__":
asyncio.run(get_async())