我在Django中具有以下文件夹结构:
./project_root
./app
./fixtures/
./static/
./templates/
./blog/
./settings.py
./urls.py
./views.py
./manage.py
./__init__.py
./plugin
./code_editor
./static
./templates
./urls.py
./views.py
./__init__.py
./code_viewer
./static
./templates
./urls.py
./views.py
./__init__.py
因此,如何通过基于INSTALLED_APPS查找其他urls.py来使根urls.py自动建立URL列表?我更改settings.py以便动态构建INSTALLED_APPS,TEMPLATES_DIR,STATICFILES_DIRS。(这意味着我不知道将在不同的服务器上安装多少个插件。它应该在运行时动态检查并添加它。)在:
python manage.py runserver
这是用于添加INSTALLED_APPS,TEMPATES_DIR,STATICFILES_DIR的代码。
PLUGINS_DIR = '/path_to/plugins/'
for item in os.listdir(PLUGINS_DIR):
if os.path.isdir(os.path.join(PLUGINS_DIR, item)):
plugin_name = 'app.plugins.%s' % item
if plugin_name not in INSTALLED_APPS:
INSTALLED_APPS = INSTALLED_APPS+(plugin_name,)
template_dir = os.path.join(PLUGINS_DIR, '%s/templates/' % item)
if os.path.isdir(template_dir):
if template_dir not in TEMPLATE_DIRS:
TEMPLATE_DIRS = TEMPLATE_DIRS+(template_dir,)
static_files_dir = os.path.join(PLUGINS_DIR, '%s/static/' % item)
if os.path.isdir(static_files_dir):
if static_files_dir not in STATICFILES_DIRS:
STATICFILES_DIRS = STATICFILES_DIRS + (static_files_dir,)
任何帮助将不胜感激。先感谢您。
解:
编辑:所以我做了如下:
我包括两个这样的模块:
from django.conf import settings
from django.utils.importlib import import_module
然后在根urls.py中添加以下代码:
def prettify(app):
return app.rsplit('.', 1)[1]
for app in INSTALLED_APPS:
try:
_module = import_module('%s.urls' % app)
except:
pass
else:
if 'eats.plugins' in app:
urlpatterns += patterns('',
url(r'^plugins/%s/' % prettify(app), include('%s.urls' % app))
)
非常感谢@Yuka。谢谢。谢谢。谢谢。谢谢你....你让我的一天。
您想要的是这样的东西:
from django.utils.importlib import import_module
for app in settings.INSTALLED_APPS:
try:
mod = import_module('%s.urls' % app)
# possibly cleanup the after the imported module?
# might fuss up the `include(...)` or leave a polluted namespace
except:
# cleanup after module import if fails,
# maybe you can let the `include(...)` report failures
pass
else:
urlpatterns += patterns('',
url(r'^%s/' % slugify(app), include('%s.urls' % app)
)
您还将想要slugify
从django模板或utils中窃取并实现自己的工具(我现在不太确定它们现在在哪里吗?),并对其稍加修改以去除任何“点”和其他不需要的命名空间在您的“网址”中,例如,您可能不希望自己的网址看起来像这样:“ example.com/plugin.some_plugin_appname/”,但喜欢example.com/nice_looking_appname/
您甚至可能根本不想为其自动命名,而是在插件自己的“设置”模块中进行可配置的“设置”或类似的操作:
# plugin settings conf
url_namespace = 'my_nice_plugin_url/'
# root urls.py:
url(r'^%s/' % mod.url_namespace, include(...))
# or:
url(r'^%s/' % app.settings.url_namespace, inc..
您可能会明白要点。
亲切的问候,
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句