import os import shutil import datetime import settings def backuppath(date = None): '''Return backup file name for datetime.date instance date, or if date is None, for today.''' if not date: date = datetime.date.today() filename = date.strftime("backup-%Y-%m-%d.db") backupdir = settings.parser.get('DEFAULT', 'backupdir') return os.path.join(backupdir, filename) def cleanbackups(): '''Clean old backups. Get backupdir and the number of backups to keep from ConfigParser.''' backupdir = settings.parser.get('DEFAULT', 'backupdir') count = settings.parser.get('DEFAULT', 'keepbackups') files = os.listdir(backupdir) files = [f for f in files if f.startswith('backup-') and f.endswith('.db')] files.sort() # Oldest first if len(files) <= count: return removefiles = files[:(len(files) - count)] for f in removefiles: os.remove(f) def dobackup(): '''Backup database. Get database location and backupdir from ConfigParser.''' backupdir = settings.parser.get('DEFAULT', 'backupdir') if not os.path.isdir(backupdir): os.mkdir(backupdir) dst = backuppath() src = settings.parser.get('DEFAULT', 'dbfile') if os.path.isfile(dst): return # We already have a backup for today shutil.copyfile(src, dst)