Skip to content

Instantly share code, notes, and snippets.

@jamesdabbs
Created July 2, 2012 15:33
Show Gist options
  • Select an option

  • Save jamesdabbs/3033814 to your computer and use it in GitHub Desktop.

Select an option

Save jamesdabbs/3033814 to your computer and use it in GitHub Desktop.
A custom django-admin command to replace Heroku's db:pull command
from optparse import make_option
import os
import subprocess
import urllib2
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
# Options for this management command
make_option('-c', '--capture',
action='store_true',
dest='capture',
default=False,
help='Capture a backup of the current data.'
),
make_option('-x',
action='store_true',
dest='delete',
default=False,
help='Delete the pg_dump file when complete.'
),
make_option('-p', '--path',
dest='path',
default='local',
help='Where to store the pg_dump file.'
),
# Options passed on to Heroku
make_option('--app',
dest='app',
default=None,
help='Which Heroku app to use'
)
)
def handle(self, backup_id='', **options):
def _make_cmd(arg):
cmd = ['heroku', 'pgbackups:%s' % arg]
if options['app']:
cmd += ['--app', options['app']]
return cmd
# Capture a new backup if needed
if options['capture']:
subprocess.call(_make_cmd('capture'))
# Expose and store a public backup url
arg = 'url %s' % backup_id if backup_id else 'url'
url = subprocess.check_output(_make_cmd(arg)).strip()
# Download the dump to the location specified by -p
filename = url.split('/')[-1].split('?')[0]
filepath = os.path.join(
settings.PROJECT_ROOT, options['path'], filename)
dump = open(filepath, 'wb')
dump.write(urllib2.urlopen(url).read())
dump.close()
# Load in the dump
db = settings.DATABASES['default']
subprocess.call(['pg_restore', '--verbose', '--clean', '--no-acl',
'--no-owner', '-h', db['HOST'], '-U', db['USER'], '-d', db['NAME'],
filepath])
# Delete the dump, if required
if options['delete']:
subprocess.call('rm ' + filepath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment