Backing up a Django app's PostgreSQL database using kronos

Tags: kronos

I have posted previously (Using Kronos to simplify cron jobs in Django) about how great kronos is and I thought I would share how I make local back ups for this website.

You can use kronos to run management commands or regular python functions as cron jobs.  This of course means you can run bash scripts too.  You just use python's subprocess module inside a regular python function!

# in app/
import subprocess
import kronos

@kronos.register('30 1 * * *')
def DoBackup():
    subprocess.check_output('/path/to/', shell=True)

I have a 'my_data_backups' directory in my django app to store my database backups.

Below is the contents of ''.  Make sure it is executable!

# Location to place backups.
#String to append to the name of the backup files
backup_date=`date +%Y-%m-%d`
#Numbers of days you want to keep copies of your database
#Name of backup file which will have the date appended

export PGPASSWORD=my-postgres-password
pg_dump db_name -U db_user -h localhost --clean -f $backup_dir$i\_$backup_date 2>&1
find $backup_dir -type f -prune -mtime +$number_of_days -exec rm -f {} \;

This script will make a back up with a file name like 'my_django_project_2017-05-20' and put it in /path/to/project/my_data_backups/.  It will then find and delete files in 'my_data_backups' that are more than 30 days old.

Make sure to replace 'db_name', 'db_user' and 'my-postgres-password' with your own database name, postgres user and password...

Loading comments...