Database backup with admin command

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# -*- encoding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
import os


DATABASES = settings.DATABASES
PROJECT_DIR = settings.PROJECT_DIR
""" PROJECT_DIR is a personal var, value is:
PROJECT_DIR = os.path.realpath(os.path.dirname(__file__))
in a file in root of project and in settings import this file.
/project
    file_with_project_dir.py
    /project
        settings.py """

class Command(BaseCommand):
    help = "Create backup of database"
    args = "[database]"

    def handle(self, *args, **options):
        # Extraemos la configuración de la base de datos indicada
        db_settings = DATABASES[args[0]]
        # Filtramos el tipo a partir del motor Django usado
        db_type = db_settings['ENGINE'].split('.')[-1].split('_')[0]
        # Formamos el nombre de archivo de respaldo con el nombre de la BD
        db_file = '/' + args[0] + '.sql'
        # Comando de exportación para SQLite3
        if db_type == 'sqlite3':
            db_command = 'sqlite3 ' + db_settings['NAME'] + ' .dump > ' + \
                settings.PRIVATE_ROOT + db_file
        # Comando de exportación para PostgreSQL
        elif db_type == 'postgresql':
            db_command = 'PGUSER=' + db_settings['USER'] + ' PGPASSWORD=' + \
                db_settings['PASSWORD'] + ' pg_dump ' + db_settings['NAME'] + \
                ' > ' + settings.PRIVATE_ROOT + db_file
        # Comando de exportación para MySQL
        elif db_type == 'mysql':
            db_command = 'mysqldump --opt --user=' + db_settings['USER'] + \
                ' --password=' + db_settings['PASSWORD'] + \
                db_settings['NAME'] + ' > ' + settings.PRIVATE_ROOT + db_file
        # Mantenemos el respaldo anterior con la extensión .old
        os.system('rm -f ' + settings.PRIVATE_ROOT + db_file + '.old')
        try:
            os.system('cp ' + settings.PRIVATE_ROOT + db_file + ' ' + \
                settings.PRIVATE_ROOT + db_file + '.old')
        except:
            pass
        os.system('rm -f ' + settings.PRIVATE_ROOT + db_file)
        # Realizamos la copia de seguridad de la base de datos
        os.system(db_command)

More like this

  1. backupdb command by msaelices 5 years, 10 months ago
  2. SQLite database vacuum script by pbx 6 years, 11 months ago
  3. Prefetch id for Postgresql backend by bretth 2 years ago
  4. Database Cache Management View by kedare 5 years, 4 months ago
  5. Serializing booleans correctly when doing dumpdata from a MySQL database using Django 0.96 by chrj 5 years, 9 months ago

Comments

(Forgotten your password?)