django如何将字符串转换为模块 [英] How does django convert string to modules
问题描述
我试图了解有关django的另一个神奇之处:它可以将字符串转换为模块。
I am trying to understand an other magic thing about django: it can convert strings to modules.
在settings.py中,INSTALLED_APPS的声明如下: p>
In settings.py, INSTALLED_APPS is declared like that:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
)
所有包含的字符串。但是django会将这些字符串转换为模块,并在以后导入。
All it contains is strings. But django will convert those strings to modules and import them later.
我希望能够做同样的事情。但我不知道如何
我在settings.py中有一个渲染器调度程序字典:
I want to do be able to do the same thing. but i don't know how. I have a dictionary of renderer dispatcher in settings.py:
RESOUCE_RENDERER = {
'video': 'video_player',
'audio': 'audio_player',
}
我想以后像这样使用它: RESOURCE_RENDERER ['video'](MyVideo)
。
I want to use it later like this: RESOURCE_RENDERER['video'](MyVideo)
.
我不能直接分配函数名称(例如video_player),因为它位于需要settings.py的模块中。
I cannot assign directly the function name(eg video_player) because it lives in a module that needs settings.py.
推荐答案
从Django 1.7开始是一个简单的功能。例如:
Since Django 1.7 there is a simple function for this. For example:
from django.utils.module_loading import import_string
my_module = import_string('path.to.my_module')
您还可以从模块中获取类:
You can also get classes from the module:
MyClass = import_string('path.to.my_module.MyClass')
这篇关于django如何将字符串转换为模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!