-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
87 lines (64 loc) · 2.48 KB
/
utils.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
import datetime
import os
import json
from typing import Union
from config import logger, settings, SAVING
@logger.catch
def save_data_to_json(data: Union[dict, list], file_name: str = "data.json", key: str = 'w'):
folder_for_saving = 'logs/saved_files'
if not os.path.exists(folder_for_saving):
os.mkdir(folder_for_saving)
path: str = f"{folder_for_saving}/{file_name}"
if key == 'w':
with open(path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
elif key == 'a':
result = {}
if os.path.exists(path):
with open(path, 'r', encoding='utf-8') as f:
result: dict = json.load(f)
if isinstance(result, list) and isinstance(data, list):
result.extend(data)
elif isinstance(result, dict) and isinstance(data, dict):
result.update(data)
save_data_to_json(data=result, file_name=file_name, key='w')
if settings.DEBUG and SAVING:
logger.debug(f"{path} saved.")
@logger.catch
def save_data_to_txt(data: Union[dict, list], file_name: str = "data.json"):
with open(file_name, 'w', encoding='utf-8') as f:
data = "\n".join(data)
f.write(data)
if settings.DEBUG and SAVING:
logger.debug(f"{file_name} saved.")
@logger.catch
def check_is_int(text: str) -> int:
"""Returns type integer number if can else zero"""
if text.isdigit():
if int(text) > 0:
return int(text)
return 0
@logger.catch
def load_statistics(filename: str = 'errors.txt') -> list[str]:
filepath = os.path.join('logs', 'saved_files', filename)
result = []
if not os.path.exists(filepath):
filepath = '..' + os.sep + filepath
if not os.path.exists(filepath):
logger.error(f"File {filepath} not found.")
return result
with open(filepath, 'r', encoding='utf-8') as f:
result: list[str] = f.readlines()
return result
@logger.catch
def get_current_time() -> datetime:
"""Возвращает текущее время целое."""
return datetime.datetime.utcnow().replace(tzinfo=None)
@logger.catch
def get_current_timestamp() -> int:
"""Возвращает текущее время (timestamp) целое."""
return int(get_current_time().timestamp())
@logger.catch
def get_from_timestamp(data: float) -> datetime:
"""Возвращает текущее время из timstamp."""
return datetime.datetime.fromtimestamp(data)