Dynamically loading modules using "from x import *" on a loaded module

I have django applications that are versioned by application name.

appv1 appv2

.Py models in applications differ slightly depending on the version, but have the same model names.

I am trying to dynamically load models into the current namespace. So I created a function that tries to get the module and return it:

def get_models_module(release):
    release_models_path = u"project.data_%s" % (release)
    _temp = __import__(release_models_path, globals(), locals(), ["models"], -1)
    models = _temp.models
    return models

Then I try to load all models from the returned models module, but it does not work.

models = get_models_module("1")
from models import *

When this happens, I get an error message:

  

ImportError: no module with model name

  

I checked, and the returned "models" object is listed as "module" project.data_1.models "...", but apparently it does not like to be renamed.

? , ?

. - .


:

Daniel Kluev , :

def load_release_models(release):
    model_release = release.replace(u".", u"_").replace(u"-", u"d") 
    release_models_path = u"project.data_%s.models" % (model_release)
    # import all release models into (global) namespace
    exec(u"from {0} import *".format(release_models_path)) in globals()

. , .

+3
1

from models import * models. "", , , .

, :

ldict = locals()
for k in models.__dict__:
    if not k.startswith('__') or not k.endswith('__'):
        ldict[k] = models.__dict__[k]

exec() ,

exec("from project.data_{0}.models import *".format(release)) in locals()
+4

Source: https://habr.com/ru/post/1757360/


All Articles