module_importer.py 2.5 KB
Newer Older
1
from mothra.settings import INSTALLED_APPS, INSTALLED_APPS_EXTERNAL_PACKAGES
2 3 4 5

appName = 'workflows'

def get_installed_apps():
6 7 8
    return list(get_local_installed_apps()) + list(get_extern_installed_apps())

def get_local_installed_apps():
9 10
    return [name[len(appName)+1:] for name in INSTALLED_APPS if name.startswith(appName+'.') and len(name)>len(appName)+1]

11 12 13
def get_extern_installed_apps():
    return INSTALLED_APPS_EXTERNAL_PACKAGES

14 15 16 17 18 19 20 21
#Following functions deal with imports of libraries as dicts
def import_all_packages_libs_as_dict(libName):
    pckLibs = {}
    for pck in get_installed_apps():
        pckLibs[pck] = import_package_lib_as_dict(pck, libName)
    return pckLibs

def import_package_lib_as_dict(packageName, libName):
22 23 24 25
    if packageName in get_local_installed_apps():
        return dynamic_import_globals_as_dict(appName+"."+packageName + "." + libName, packageName)
    else:
        return dynamic_import_globals_as_dict(packageName + "." + libName, packageName)
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

def dynamic_import_globals_as_dict(name, package):
    try:
        m = __import__(name, globals(), locals(), ['*'])
    except:
        return None
    return m

#Following functions deal with imports of libraries as globals, hovever localSetAttrFunc must be provided - this function should set local global in file where we want import like:
#def setattr_local(name, value, package):
#    setattr(sys.modules[__name__], name, value)
def import_all_packages_libs(libName, localSetAttrFunc):
    for pck in get_installed_apps():
        import_package_lib(pck, libName, localSetAttrFunc)

def import_package_lib(packageName, libName, localSetAttrFunc):
42 43 44 45 46
    if packageName in get_local_installed_apps():
        dynamic_import_globals(appName+"."+packageName + "." + libName, packageName, localSetAttrFunc)
    else:
        # External CF package
        dynamic_import_globals(packageName + "." + libName, packageName, localSetAttrFunc)
47 48

def dynamic_import_globals(name, package, localSetAttrFunc):
Janez K's avatar
Janez K committed
49
    m = None
50 51
    try:
        m = __import__(name, globals(), locals(), ['*'])
Janez K's avatar
Janez K committed
52 53
    except ImportError:
        pass
54
    except:
Janez K's avatar
Janez K committed
55 56 57 58 59
        import sys, traceback
        print "Exception in user code:"
        print '-'*60
        traceback.print_exc(file=sys.stdout)
        print '-'*60
60 61 62 63 64 65
        return
    all_names = [name for name in dir(m) if name[0]!='_']
    g = globals()
    for name in all_names:
        #g[name] = m.__dict__.get(name)
        localSetAttrFunc(name, m.__dict__.get(name), package)