Created
February 13, 2017 19:07
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
import bisect | |
import os | |
import sys | |
from importlib import import_module | |
from django.apps import apps | |
from django.core.management import BaseCommand | |
from common.logging.logging_util import LoggerHelper | |
from pets import settings | |
class Command(BaseCommand): | |
help = 'Install Demo Data from all Applications' | |
def __init__(self, *args, **kwargs): | |
super(Command, self).__init__(*args, **kwargs) | |
LoggerHelper.initialize_app_loggers() | |
def handle(self, *args, **options): | |
self.stdout.write('Installing Demo Data') | |
ordered_by_priority = [] | |
demo_modules = self.get_demodata_modules() | |
for dmodule in demo_modules: | |
inst = dmodule.DemoData() | |
bisect.insort_left(ordered_by_priority, inst) | |
for obp in ordered_by_priority: | |
print "Install: "+obp.__module__ + "."+obp.__class__.__name__ | |
print "Priority: "+str(obp.priority) | |
obp.install() | |
def get_demodata_modules(self): | |
""" | |
Return a list of demo data modules. | |
The list contains the 'demo' subdirectory of each installed | |
application. | |
""" | |
demo_data_modules = [] | |
for app_config in apps.get_app_configs(): | |
app_label = app_config.label | |
if app_label in settings.ESPRESSIVE_APPS: | |
module_name = app_label + ".demo" | |
was_loaded = module_name in sys.modules | |
try: | |
module = import_module(module_name) | |
except ImportError as e: | |
continue | |
else: | |
# needed for tests | |
if was_loaded: | |
reload(module) | |
directory = os.path.dirname(module.__file__) | |
# Scan for .py files | |
demo_names = set() | |
print app_label + " has a demo" | |
for name in os.listdir(directory): | |
if name.endswith(".py"): | |
import_name = name.rsplit(".", 1)[0] | |
if import_name[0] not in "_.~": | |
demo_names.add(import_name) | |
print demo_names | |
for demo_name in demo_names: | |
migration_module = import_module("%s.%s" % (module_name, demo_name)) | |
if not hasattr(migration_module, "DemoData"): | |
raise Exception( | |
"DemoData %s in app %s has no DemoData class" % (demo_name, app_config.label) | |
) | |
demo_data_modules.append(migration_module) | |
return demo_data_modules |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment