我在 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
那么,我怎样才能让 root urls.py 通过查找基于 INSTALLED_APPS 的其他 urls.py 自动构建 url 列表?我更改 settings.py 以动态构建 INSTALLED_APPS、TEMPLATES_DIR、STATICFILES_DIRS。 (这意味着我不知道在不同的服务器上会安装多少插件。它应该在运行时动态检查它并添加它。)on:
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,)
任何帮助将不胜感激。提前谢谢你。
SOLUTION:
EDIT: So what i did are as following:
I include two modules like this:
from django.conf import settings
from django.utils.importlib import import_module
And then in root urls.py I add following code:
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))
)
Thank you a lot @Yuka. Thank you. Thank you. Thank you. Thank you.... You make my day.
最佳答案
你想要的是这样的:
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)
)
您还想从 django 模板或实用程序中窃取并实现您自己的 slugify
(我不太确定这些天它在哪里?)并稍微修改它以去除任何 '点”和其他你不希望在你的“url”中使用的无用命名空间,例如你可能不希望你的 url 看起来像这样:'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..
你可能已经明白了它的要点。
亲切的问候,
关于python - Django:动态添加应用程序作为插件,自动构建 url 和其他设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19833393/