Skip to content

Instantly share code, notes, and snippets.

@thoas
Forked from ericflo/backup_db.py
Created January 7, 2011 19:44
Show Gist options
  • Save thoas/769981 to your computer and use it in GitHub Desktop.
Save thoas/769981 to your computer and use it in GitHub Desktop.
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