/
O.S.Prog
/
InstrumentProtocol
Обзор
Документация
Войти
/
O.S.Prog
/
InstrumentProtocol
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
core/backup.py
77 строк
3 KB
O.S.Prog
Initial commit: InstrumentProtocol v2.0
17 июл 2026, 15:11
17 июл 2026, 15:11
1e845bd
Код
Авторство
О чём код?
import os import zipfile import base64 from datetime import datetime from utils.file_utils import get_protocols_folder def create_backup(target_folder, encryption_key=None): """ Создаёт ZIP-архив всех протоколов (с сохранением папок по типам). Возвращает (успех, сообщение, количество_файлов, путь_к_архиву) """ source_root = get_protocols_folder() if not os.path.exists(source_root): return False, "Папка с протоколами не найдена.", 0, "" # Собираем все .enc файлы all_files = [] for root, dirs, files in os.walk(source_root): for f in files: if f.endswith('.enc'): all_files.append(os.path.join(root, f)) if not all_files: return False, "Нет протоколов для резервного копирования.", 0, "" # Создаём папку для бекапа, если нет if not os.path.exists(target_folder): try: os.makedirs(target_folder, exist_ok=True) except Exception as e: return False, f"Не удалось создать папку: {str(e)}", 0, "" # Имя ZIP-архива date_str = datetime.now().strftime("%Y-%m-%d_%H-%M") zip_name = f"Protocols_backup_{date_str}.zip" zip_path = os.path.join(target_folder, zip_name) try: with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf: for filepath in all_files: arcname = os.path.relpath(filepath, os.path.dirname(source_root)) zf.write(filepath, arcname) # Сохраняем ключ шифрования в архив if encryption_key: key_b64 = base64.b64encode(encryption_key).decode('ascii') zf.writestr('encryption_key.txt', key_b64) return True, f"Создан архив: {zip_name}", len(all_files), zip_path except Exception as e: return False, f"Ошибка: {str(e)}", 0, "" def restore_backup(zip_path, target_root=None): """ Восстанавливает протоколы из ZIP-архива. Возвращает (успех, сообщение, количество_файлов) """ if target_root is None: target_root = os.path.dirname(get_protocols_folder()) if not os.path.exists(zip_path): return False, "Архив не найден.", 0 try: with zipfile.ZipFile(zip_path, 'r') as zf: file_list = [f for f in zf.namelist() if f.endswith('.enc')] if not file_list: return False, "В архиве нет протоколов.", 0 zf.extractall(target_root) return True, f"Восстановлено {len(file_list)} протоколов.", len(file_list) except Exception as e: return False, f"Ошибка восстановления: {str(e)}", 0