How to access a python module variable using a string [ django ]

雨燕双飞 提交于 2019-12-08 16:01:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!