Skip to content

Instantly share code, notes, and snippets.

@TylerRudie
Last active September 23, 2019 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TylerRudie/66d1ca7657c1e543bdd3361ea25eb610 to your computer and use it in GitHub Desktop.
Save TylerRudie/66d1ca7657c1e543bdd3361ea25eb610 to your computer and use it in GitHub Desktop.
Django Backup Core
from django.apps import apps
from django.utils.timezone import now
from django.conf import settings
from os import mkdir
import subprocess
import shutil
outputBase = '/path/to/local/working/folder'
def backupModel(target, time):
subprocess.check_call(['python',
'manage.py',
'dumpdata',
'--natural-foreign',
'--natural-primary',
target,
'--indent',
'4',
'--output',
'{}{}/{}_{}.json'.format(outputBase,
time.strftime("%Y%m%d_%H%m"),
target,
time.strftime("%Y%m%d_%H%m")),
])
def tarFolder(target, filename):
subprocess.check_call(['tar', '-zcf', filename, target, ])
def fullBackup():
blacklist = ['django_celery_beat',
'fullcalendar']
b = now()
mkdir('{}{}'.format(outputBase,
b.strftime("%Y%m%d_%H%m")))
tarFileName = '{}{}_dbBackup.tar.gz'.format(outputBase,
b.strftime("%Y%m%d_%H%m"))
for app in settings.INSTALLED_APPS:
if app not in blacklist:
for k in apps.all_models[app]:
print("{}, {}".format(app, k))
backupModel(target = '{}.{}'.format(app, k),
time = b)
backupModel(target = 'auth',
time = b
)
backupModel(target = 'authtoken',
time = b
)
backupModel(target='contenttypes', time=b)
try:
shutil.copytree(settings.MEDIA_ROOT,
'{}{}/media/'.format(outputBase,
b.strftime("%Y%m%d_%H%m")),
ignore = shutil.ignore_patterns('*.tgz.gpg')
)
tarFolder(target= '{}{}/'.format(outputBase,
b.strftime("%Y%m%d_%H%m")),
filename= tarFileName)
shutil.rmtree('{}{}'.format(outputBase,
b.strftime("%Y%m%d_%H%m")
)
)
except Exception as e:
print(e)
from toolLocker.tasks.djangoBackup import fullBackup
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Starts Full Backup Process'
def add_arguments(self, parser):
pass
def handle(self, *args, **kwargs):
fullBackup()
print('### Backup Complete ###')
@drewbrew
Copy link

Q: Why did you choose to drop to a shell instead of running call_command?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment