-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
120 lines (96 loc) · 4.1 KB
/
main.py
File metadata and controls
120 lines (96 loc) · 4.1 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
import os
from datetime import datetime
import requests
import time
from tqdm import tqdm
class API:
url_users: str = "https://json.medrating.org/users"
url_todos: str = "https://json.medrating.org/todos"
def users(self):
try:
users_request = requests.get(self.url_users)
users = users_request.json()
return users
except requests.exceptions.ConnectionError:
print("Не удалось получить список пользователей.")
return None
def get_user(self, user_id: int):
try:
user_request = requests.get(f"{self.url_users}/{user_id}")
user = user_request.json()
return user
except requests.exceptions.ConnectionError:
return None
def user_todos(self, user_id: int):
try:
user_todos = requests.get(f"{self.url_todos}/?userId={user_id}")
todos = user_todos.json()
return todos
except requests.exceptions.ConnectionError:
print("Не удалось получить список задач.")
return None
class Write:
def __init__(self, directory_name: str = "tasks"):
self.users = None
self.directory_name = directory_name
self.api_hand = API()
self.set_users()
def mkdir(self):
try:
if not os.path.exists(self.directory_name):
os.mkdir(self.directory_name)
return True
except OSError:
print("Ошибка при создании директории.")
return False
def set_users(self):
self.users = self.api_hand.users()
def todo(self, user):
user_todos = self.api_hand.user_todos(user['id'])
completed_todos = list(filter(lambda todo: todo['completed'], user_todos))
uncompleted_todos = list(filter(lambda todo: not todo['completed'], user_todos))
return user_todos, completed_todos, uncompleted_todos
@staticmethod
def todo_title(todo: dict):
if len(todo['title']) > 48:
todo['title'] = f"{todo['title'][:48]}..."
return todo['title']
def user_record(self, user: dict):
user_todos, completed_todos, uncompleted_todos = self.todo(user)
record = f"Отчёт {user['company']['name']}.\n"
record += f"{user['name']} <{user['email']}> {datetime.now().strftime('%d.%m.%Y %H:%M:%S')}\n"
record += f"Всего задач: {len(user_todos)}\n\n"
record += f"Завершённые задачи ({len(completed_todos)}):\n"
for completed_todo in completed_todos:
record += f"{self.todo_title(completed_todo)}\n"
record += "\n"
record += f"Оставшиеся задачи ({len(uncompleted_todos)}):\n"
for uncompleted_todo in uncompleted_todos:
record += f"{self.todo_title(uncompleted_todo)}\n"
return record
def user_file_name(self, user: dict):
filename = f"{user['username']}"
if os.path.exists(f"{self.directory_name}/{filename}.txt"):
created_at = os.path.getmtime(f"{self.directory_name}/{filename}.txt")
created_at = datetime.strptime(time.ctime(created_at), "%a %b %d %H:%M:%S %Y")
os.renames(f"{self.directory_name}/{filename}.txt",
f"{self.directory_name}/old_{filename}_{created_at.strftime('%Y-%m-%dT%H-%M-%S')}.txt")
return f"{filename}.txt"
def write(self):
if self.mkdir():
for user in self.users:
with open(
f"{self.directory_name}/{self.user_file_name(user)}", 'w', encoding="utf-8"
) as user_file:
record = self.user_record(user)
user_file.write(record)
def run(self):
self.write()
if __name__ == "__main__":
writ = Write()
writ.run()
mylist = [1, 2, 3, 4, 5]
for i in tqdm(mylist):
time.sleep(1)
print('Задача выполнена, смотрите папку tasks\n'
'Всего хорошего и до новых встреч!')