我正在尝试编写一些代码,以便在我的django项目中动态导入“类似插件”的应用程序。我正在使用Django 1.10
我将django.apps.AppConfig
类子类化并用它来标记插件:
from django.apps import AppConfig
class AutomationAppConfig(AppConfig):
def get_url(self):
return self.name
然后,在我的项目主urls.py中,我在主要的“静态”urlpatterns initializazion之后添加了这段代码:
...
from slae.util import AutomationAppConfig
from django.apps import apps
for module in iter(apps.get_app_configs()):
if isinstance(module, AutomationAppConfig):
url = module.get_url()
urlpatterns.append(url(r'^%s/' % url, include('%s.urls' % module.name), name = module.name))
但是当服务器(重新)加载
时,它会出现以下错误...
File "/cygdrive/d/workspaces/non-ide/slae/slae/urls.py", line 47, in <module>
urlpatterns.append(url(r'^%s/' % url, include('%s.urls' % module.name), name = module.name))
TypeError: 'str' object is not callable
我不明白的是,使用此代码可以正常工作:
from slae.util import AutomationAppConfig
from . import settings
from django.utils.module_loading import import_string
import inspect
for app in settings.INSTALLED_APPS:
try:
module = import_string(app)
except:
pass
else:
if inspect.isclass(module) and issubclass(module, AutomationAppConfig):
urlpatterns.append(url(r'^%s/' % module.name, include('%s.urls' % module.name), name = module.name))
我错过了什么?
答案 0 :(得分:2)
from django.conf.urls
是url = module.get_url()
中定义的函数。但是,代码中的以下行将覆盖此变量并在其中存储字符串。
url_route = module.get_url()
urlpatterns.append(url(r'^%s/' % url_route, include('%s.urls' % module.name), name = module.name))
将此变量更改为其他内容,例如:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "showPasscodeView:", name: UIApplicationWillEnterForegroundNotification, object: nil)