Skip to content

Instantly share code, notes, and snippets.

@ericflo
Created January 5, 2011 18:25
Show Gist options
  • Save ericflo/766727 to your computer and use it in GitHub Desktop.
Save ericflo/766727 to your computer and use it in GitHub Desktop.
A management command to put on a cron to keep daily backups of a postgres database (with a 1-week window)
import datetime
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
from boto.s3.connection import S3Connection
from boto.s3.key import Key
class Command(BaseCommand):
help = "Backs up the database and uploads it to S3"
def handle(self, *app_labels, **options):
filename = '%s.dump' % (datetime.date.today(),)
filepath = '/tmp/%s' % (filename,)
old_filename = '%s.dump' % (
datetime.date.today() - datetime.timedelta(days=7),)
cmd = [
'pg_dump',
'-h',
settings.DATABASE_HOST,
'-p',
settings.DATABASE_PORT,
'-c',
'-Fc',
'-Z9',
settings.DATABASE_NAME,
]
with open(filepath, 'w') as f:
with open(filepath + '.err', 'w') as err_f:
proc = subprocess.Popen(cmd, stdout=f, stderr=err_f)
proc.wait()
conn = S3Connection(settings.AWS_ACCESS_KEY_ID,
settings.AWS_SECRET_ACCESS_KEY)
bucket_name = settings.AWS_STORAGE_BUCKET_NAME + '-db'
bucket = conn.get_bucket(bucket_name)
k = Key(bucket)
k.key = filename
k.set_contents_from_filename(filepath)
# Delete the week old backup
try:
old = Key(bucket)
old.key = old_filename
old.delete()
except (KeyboardInterrupt, SystemExit):
raise
except:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment