问题
I have a django application, with a module called "app"
Now this module has a file called "urls.py" which has a variable called "HOME_URL"
What I'm trying to do ?
app_label = "app"
url = __import__(app_label).urls.HOME_URL
print url
That obviously doesn't work, but I hope you got what I'm trying to do, If not please comment I will edit the question to contain more info.
回答1:
You can use import_module to load a module relative to the root of a django project.
from django.utils.importlib import import_module
app_label = "app"
url = import_module("%s.urls" % app_label).HOME_URL
This should work within your django project, or in ./manage.py shell
.
回答2:
If you're using Django 1.7+, you should use import_string instead.
from django.utils.module_loading import import_string
app_label = "app"
url = import_string("%s.urls.HOME_URL" % app_label)
By the way, some clarifications about Python modules and packages.
A package is a folder containing files, including one file called __init__.py
. It sounds your 'app' 'module' is actually a package.
A module is a .py
file within a package. So your urls.py
is actually a module.
来源:https://stackoverflow.com/questions/7121983/how-to-access-a-python-module-variable-using-a-string-django