在Django的执行阶段修改urlpatterns

use*_*007 5 django url-pattern

我正在开发需要加载动态模块(在运行时)的Django应用程序。现在,我可以上载(从客户端浏览器到服务器)“插件”并在数据库中注册插件模型,等等。但是我需要一种方法来处理每个插件的urlpatterns。当前,我已经在webapp的“核心”中编写了一个函数,该函数注册了一个模型,并(通过理论上)通过包含该插件将上传插件的urlpatterns添加到了webapp urls.py中。该函数是:

def register_plugin_model(model,codename):
# Standard syncdb expects models to be in reliable locations,
# so dynamic models need to bypass django.core.management.syncdb.
# On the plus side, this allows individual models to be installed
# without installing the entire project structure.
# On the other hand, this means that things like relationships and
# indexes will have to be handled manually.
# This installs only the basic table definition.

if model is not None:
    style = color.no_style()
    cursor = connection.cursor()
    tables = connection.introspection.table_names()
    seen_models = connection.introspection.installed_models(tables)
    statements,trsh = connection.creation.sql_create_model(model, style, seen_models)
    for sql in statements:
        cursor.execute(sql)

# add urlpatterns
from django.conf.urls.defaults import patterns, url,include
from project.plugins.urls import urlpatterns
urlpatterns += patterns(url(r'^' + codename + '/' , include ( 'media.plugins.' + codename + '.urls' )))
Run Code Online (Sandbox Code Playgroud)

插件以tgz格式上传到“ media / tmp”,然后解压缩到“ media / plugins /”(插件的代号),用户上传的插件由“ project.plugins”管理。

所有插件逻辑都可以正常工作,但是当我尝试将上传的插件urls.py文件包含到webapp(project.plugins.urls)中时,它无效。我已经打印了“ project.plugins.urls.urlpatterns”的值,并且在“ urlpatterns + = pat ....”之后没有被修改。

有什么办法可以做我需要的吗?

最好的祝福

Jos*_*ton 4

您面临的问题是urlpatterns在您的项目url.py文件中定义的,并且urlpatterns在您的register_plugin文件中定义的是不同的变量。它们是模块本地的。想象一下以下场景:

#math.py
pi = 3.14

#some_nasty_module.py
from math import pi
pi = 'for_teh_luls'

#your_module.py
from math import pi
pi * 2
>>> 'for_teh_lulsfor_teh_luls'
# wtf?
Run Code Online (Sandbox Code Playgroud)

显然你不被允许这样做。您可能需要做的是要求原件urls.py尝试在您的插件文件夹中发现网址。

# urls.py
urlpatterns += (...)

def load_plugin_urls():
    for module in get_plugin_modules():
        try:
            from module.urls import urlpatterns as u
            urlpatterns += u
        except:
            pass
Run Code Online (Sandbox Code Playgroud)

不幸的是,网络服务器需要回收该代码才能运行的进程,因此插件的上传只有在发生这种情况后才会生效。