Notes/src/backup.py

53 lines
1.3 KiB
Python
Raw Normal View History

2017-10-09 19:48:10 -04:00
import os
import re
from datetime import datetime
2017-10-09 19:48:10 -04:00
from shutil import copyfile
import config_provider
2017-10-09 19:48:10 -04:00
import utils
from sql import get_option, set_option, commit
2017-10-09 16:50:36 -04:00
def regular_backup():
2017-10-09 19:48:10 -04:00
now = utils.now_timestamp()
last_backup_date = int(get_option('last_backup_date'))
if now - last_backup_date > 43200:
2017-10-09 16:50:36 -04:00
backup_now()
2017-10-09 16:50:36 -04:00
cleanup_old_backups()
2017-10-09 19:48:10 -04:00
2017-10-09 16:50:36 -04:00
def backup_now():
2017-10-09 19:48:10 -04:00
now = utils.now_timestamp()
2017-10-09 19:48:10 -04:00
config = config_provider.get_config()
2017-10-09 16:50:36 -04:00
document_path = config['Document']['documentPath']
backup_directory = config['Backup']['backupDirectory']
2017-10-09 16:50:36 -04:00
date_str = datetime.utcnow().strftime("%Y-%m-%d %H:%M")
2017-10-06 20:39:00 -04:00
2017-10-09 16:50:36 -04:00
copyfile(document_path, backup_directory + "/" + "backup-" + date_str + ".db")
2017-10-06 20:39:00 -04:00
2017-10-09 19:48:10 -04:00
set_option('last_backup_date', now)
2017-10-09 16:50:36 -04:00
commit()
2017-10-06 20:39:00 -04:00
2017-10-09 19:48:10 -04:00
2017-10-06 20:39:00 -04:00
def cleanup_old_backups():
now = datetime.utcnow()
2017-10-09 19:48:10 -04:00
config = config_provider.get_config()
2017-10-06 20:39:00 -04:00
backup_directory = config['Backup']['backupDirectory']
for file in os.listdir(backup_directory):
match = re.search(r"backup-([0-9 -:]+)\.db", file)
if match:
date_str = match.group(1)
date = datetime.strptime(date_str, "%Y-%m-%d %H:%M")
if (now - date).days > 30:
print("Removing old backup - " + file)
os.remove(backup_directory + "/" + file)