I have lots of
from myproject.settings import param1
from myproject.settings import ...
scattered all over my project.
Upon startup, I would like to load different "settings" module according to env var (for example export SETTINGS=myproject.settings2)
I tried to put in the myproject.__init__.py
someting like
module_name = os.environ['SETTINGS']
m=__import__(module_name)
settings = m
but it won't work.
from myproject.settings import *
ImportError: No module named settings
How can this be achieved ?
4 Answers 4
Try using a bogus 'fromlist' argument.
mymodule = __import__(mod, fromlist=['a'])
It's worked for me before in situations similar to yours.
Comments
settings = __import__(os.environ['SETTINGS'])
but it won't work.
Why? Your approach is the right one. As example, Django does this the same way.
You could try to add the absolute path of myproject.settings to PYTHONPATH like so:
PYTHONPATH=$PYTHONPATH:$HOME/myproject/settings/
export PYTHONPATH
Now you could keep this in ~/.bashrc (assuming UNIX env). This way whenever you open a new terminal this path is added to PYTHONPATH. i.e. python interpretor would add this path to it's like of paths to look for while importing a module.
Now whichever path you are simply type import settings & since myproject/settings is present python would load settings file.
Hope this helps...
Comments
I tried the code below and it worked.
Here is my folder structure:
src/
app.py
settings/
__init__.py
production.py
sandbox.py
In settings.__init__.py, I wrote:
import os
settings_module = os.environ.get('APP_SETTINGS')
if not settings_module:
from .sandbox import *
else:
exec('from {} import *'.format(settings_module))
If the var env was not set, imports the sandbox module. If was setting, imports the module dynamically.
Hope this helps