Skip to content

Instantly share code, notes, and snippets.

@dokenzy
Created April 13, 2019 07:07
Show Gist options
  • Save dokenzy/3fd6e60363073abc154a680269fc9cf2 to your computer and use it in GitHub Desktop.
Save dokenzy/3fd6e60363073abc154a680269fc9cf2 to your computer and use it in GitHub Desktop.
import os
import re
import zipfile
from collections import defaultdict
from datetime import datetime
"""
Backup Django migration files
* Required Python 3.6+
"""
RE_MIG = re.compile(r'000\d_.+\.py')
DJANGO_RPOJECT_DIR = 'oniondesk'
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ONIONDESK_DIR = os.path.join(BASE_DIR, DJANGO_RPOJECT_DIR)
def get_migration_files():
"""Django 프로젝트 디렉토리에서 앱별로 migrations 파일 리스트를 만든다.
:rtype defaultdict
"""
mig_files = defaultdict(list)
for dir_name in os.listdir(ONIONDESK_DIR):
abs_dir_path = os.path.join(ONIONDESK_DIR, dir_name)
if not os.path.isdir(abs_dir_path):
continue
if dir_name == '__pycache__':
continue
abs_app_mig_dir = os.path.join(abs_dir_path, 'migrations')
if not os.path.exists(abs_app_mig_dir):
continue
for file_name in os.listdir(abs_app_mig_dir):
if file_name == '__pycache__':
continue
m = RE_MIG.match(file_name)
if m is None:
continue
mig_files[dir_name].append(file_name)
return mig_files
def save_mig_files_to_zip(mig_files, zipfile_name):
"""마이그레이션 파일을 zip 파일로 압축한다.
:param mig_files: 압축할 파일 리스트
:param zipfile_name: 압축파일 이름
"""
mig_zip = zipfile.ZipFile(os.path.join(zipfile_name), 'w')
for app_name in mig_files:
for mig_file in mig_files[app_name]:
arcname = os.path.join(app_name, 'migrations', mig_file)
filename = os.path.join(ONIONDESK_DIR, arcname)
mig_zip.write(filename, arcname)
if __name__ == '__main__':
mig_files = get_migration_files()
now = datetime.now().strftime('%y%m%d-%H%M')
zip_file_name = 'migration_{}.zip'.format(now)
save_mig_files_to_zip(mig_files, zip_file_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment