HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonMinor

Create SQLite backups

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sqlitebackupscreate

Problem

I have this script for creating SQLite backups, and I was wondering whether you'd have any suggestions on how to improve this. I was thinking that maybe it should create the backup dir if it doesn't exist, but not sure if it's necessarily better.

Besides functionality/performance tips, any styling/formatting tips are also much appreciated.

```
#!/usr/bin/env python
"""
This script creates a timestamped database backup,
and cleans backups older than a set number of dates

"""

from __future__ import print_function
from __future__ import unicode_literals

import argparse
import sqlite3
import shutil
import time
import os

DESCRIPTION = """
Create a timestamped SQLite database backup, and
clean backups older than a defined number of days
"""

# How old a file needs to be in order
# to be considered for being removed
NO_OF_DAYS = 7

def sqlite3_backup(dbfile, backupdir):
"""Create timestamped database copy"""

if not os.path.isdir(backupdir):
raise Exception("Backup directory does not exist: {}".format(backupdir))

backup_file = os.path.join(backupdir, os.path.basename(dbfile) +
time.strftime("-%Y%m%d-%H%M%S"))

connection = sqlite3.connect(dbfile)
cursor = connection.cursor()

# Lock database before making a backup
cursor.execute('begin immediate')
# Make new backup file
shutil.copyfile(dbfile, backup_file)
print ("\nCreating {}...".format(backup_file))
# Unlock database
connection.rollback()

def clean_data(backup_dir):
"""Delete files older than NO_OF_DAYS days"""

print ("\n------------------------------")
print ("Cleaning up old backups")

for filename in os.listdir(backup_dir):
backup_file = os.path.join(backup_dir, filename)
if os.stat(backup_file).st_ctime < (time.time() - NO_OF_DAYS * 86400):
if os.path.isfile(backup_file):
os.remove(backup_file)
print

Solution

There's no need to repeat yourself by defining DESCRIPTION (and in fact your strings have gotten out of sync). Just reuse the program's docstring:

def get_arguments():
    """Parse the commandline arguments from the user"""    
    parser = argparse.ArgumentParser(description=__doc__)
    …

Code Snippets

def get_arguments():
    """Parse the commandline arguments from the user"""    
    parser = argparse.ArgumentParser(description=__doc__)
    …

Context

StackExchange Code Review Q#78643, answer score: 5

Revisions (0)

No revisions yet.