Sil*_*ght 25 python django python-import
我正在使用django的调试工具栏,如果两个条件为真,我想将它添加到项目中:
settings.DEBUG 是 True做第一个并不难
# adding django debug toolbar
if DEBUG:
MIDDLEWARE_CLASSES += 'debug_toolbar.middleware.DebugToolbarMiddleware',
INSTALLED_APPS += 'debug_toolbar',
Run Code Online (Sandbox Code Playgroud)
但是如何检查模块是否存在?
我找到了这个解决方案:
try:
import debug_toolbar
except ImportError:
pass
Run Code Online (Sandbox Code Playgroud)
但由于导入发生在django的其他地方,我需要if/else逻辑来检查模块是否存在,所以我可以在settings.py中检查它
def module_exists(module_name):
# ??????
# adding django debug toolbar
if DEBUG and module_exists('debug_toolbar'):
MIDDLEWARE_CLASSES += 'debug_toolbar.middleware.DebugToolbarMiddleware',
INSTALLED_APPS += 'debug_toolbar',
Run Code Online (Sandbox Code Playgroud)
有办法吗?
Sve*_*ach 43
您可以在函数中使用相同的逻辑:
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return True
Run Code Online (Sandbox Code Playgroud)
此解决方案没有性能损失,因为模块仅导入一次.