Trying to dynamically add settings attributes to globals()
according to some dynamic environment variables.
import os
from importlib import import_module
# To support environment variables as the means of specifying
# the target environment as an alternative to using the --settings flag
# where MY_ENV is 'local', 'development', 'staging', 'production'
if os.environ.get('MY_ENV'):
env = os.environ.get('MY_ENV')
import_module('my.settings.%s' % env, '*')
Its understood that import_module
needs to be assigned to a variable:
foo = import_module('path.to.package', 'bar')
and that:
globals()[foo] = foo
can add this to the global
scope.
However, what is to be done with the wildcard *
?
globals()[*] = import_module('path.to.package', '*')
Obviously, the above causes a syntax error.
to do what you want, you need to use "__import__()" and not import_module()
I think this answer can help you
How can I import a package using __import__() when the package name is only known at runtime?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With