Last active
September 23, 2019 20:21
-
-
Save TylerRudie/66d1ca7657c1e543bdd3361ea25eb610 to your computer and use it in GitHub Desktop.
Django Backup Core
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ###') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Q: Why did you choose to drop to a shell instead of running
call_command
?