Detect type of database (MySQL, PostgreSQL or SQLite) and make backup. In this moment ONLY WORK in GNU/Linux, NOT WIN.
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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.