- Index: backupdb.py
- ===================================================================
- --- backupdb.py (revision 465)
- +++ backupdb.py (working copy)
- @@ -1,9 +1,12 @@
- """
- Command for backup database
- """
- +import bz2
- import os, time
- +from optparse import make_option
- +
- import pexpect
- from django.core.management.base import BaseCommand
- @@ -11,6 +14,18 @@
- class Command(BaseCommand):
- help = "Backup database. Only Mysql and Postgresql engines are implemented"
- + option_list = BaseCommand.option_list + (
- + make_option('-c', '--compress', action='store_true', dest='compress_backup',
- + help='Makes a compressed backup of the current database.'),
- + )
- +
- + def bz2_backup(self, data, outfile):
- + file = bz2.BZ2File(outfile, "wb")
- + try:
- + file.write(data)
- + finally:
- + file.close()
- +
- def handle(self, *args, **options):
- from django.conf import settings
- @@ -25,17 +40,21 @@
- if not os.path.exists(backup_dir):
- os.makedirs(backup_dir)
- outfile = os.path.join(backup_dir, 'backup_%s.sql' % time.strftime('%y%m%d%S'))
- +
- + compress_backup = options.get('compress_backup', False)
- + if compress_backup is not None:
- + outfile += '.bz2'
- if self.engine == 'mysql':
- print 'Doing Mysql backup to database %s into %s' % (self.db, outfile)
- - self.do_mysql_backup(outfile)
- + self.do_mysql_backup(outfile, compress_backup)
- elif self.engine in ('postgresql_psycopg2', 'postgresql'):
- print 'Doing Postgresql backup to database %s into %s' % (self.db, outfile)
- - self.do_postgresql_backup(outfile)
- + self.do_postgresql_backup(outfile, compress_backup)
- else:
- print 'Backup in %s engine not implemented' % self.engine
- - def do_mysql_backup(self, outfile):
- + def do_mysql_backup(self, outfile, compress_backup=False):
- args = []
- if self.user:
- args += ["--user=%s" % self.user]
- @@ -47,9 +66,14 @@
- args += ["--port=%s" % self.port]
- args += [self.db]
- - os.system('mysqldump %s > %s' % (' '.join(args), outfile))
- + #os.system('mysqldump %s > %s' % (' '.join(args), outfile))
- + sqldata = os.popen('mysqldump %s' % (' '.join(args)))
- + if compress_backup is not None:
- + self.bz2_backup(sqldata, outfile)
- + else:
- + file(outfile, 'w').write(sqldata)
- - def do_postgresql_backup(self, outfile):
- + def do_postgresql_backup(self, outfile, compress_backup=False):
- args = ['pg_dump']
- if self.user:
- args += ["--username=%s" % self.user]
- @@ -69,7 +93,10 @@
- child.sendline(self.passwd)
- child.expect(pexpect.EOF)
- - file(outfile, "w").write(child.before)
- + if compress_backup is not None:
- + self.bz2_backup(child.before, outfile)
- + else:
- + file(outfile, "w").write(child.before)
- child.close()
- else:
- os.system('%s > %s' % (cmd, outfile))