python - 带有动态前缀的 Django URL

标签 python django

我的应用中的所有网址都需要一个动态网址前缀。

我熟悉使用静态前缀,例如 url(r'^myprefix/app', include('app.urls')) .

相反,我需要 myprefix是动态的,例如 url(r'^(?P<prefix>\w+)/app', include('app.urls')) .

这行得通,但更重要的是。我不想要那个prefix作为关键字参数发送给所有 View 。我希望能够捕获它并在中间件或类似的东西中使用它。


为了给出我的具体用例,我们有用于管理各种测试实验室的软件(此 Django 项目)。该应用需要知道它在哪个实验室运行。

目前我正在使用以下方法:

class LabMiddleware(object):
    def process_request(self, request):
        request.current_lab = 'lab1'  # Note that this is currently hard coded

要求指出用户能够访问一个 URL,例如 http://host/<lab_name>/app lab_name在哪里然后会在我的 LabMiddleware 中使用。因此,我显然不想接受 lab_name在我的每一个观点中都认为它既麻烦又矫枉过正。


更新:

根据 Sohan 在他的回答中给出的内容,我最终使用了自定义中间件类:

urls.py

url(r'^(?P<lab_name>\w+)/', include('apps.urls')),

apps/urls.py

url(r'^app1/', include('apps.app1.urls', namespace='app1')),

中间件.py

class LabMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        lab_name = view_kwargs.get('lab_name')
        if lab_name:
            request.current_lab = Lab.objects.get(name=lab_name)
            # Remove the lab name from the kwargs before calling the view
            view_kwargs.pop('lab_name')
            return view_func(request, *view_args, **view_kwargs)

settings.py

MIDDLEWARE_CLASSES = (
    # Default Django middleware classes here...
    'raamp.middleware.LabMiddleware',
)

这让我可以在 URL 中包含实验室名称并将其添加到请求中。然后将其从 view_kwargs 中删除,它不会传递给 View 函数,一切都按我的预期进行。

另请注意,我上面的代码并不是最优化的(例如,我正在为每个请求查询数据库)。我删除了用于缓存此代码的代码,因为这对于展示如何解决此问题并不重要,但值得一提的是,如果您在生产系统中使用此代码,则应对其进行一些改进。

最佳答案

您可以创建一个装饰器来包装每个 View 函数。装饰器可以处理您对实验室名称参数的任何处理工作,并且每个 View 都不需要看到 lab_name。参数。

def process_lab_name(request, lab_name):
    request.current_lab = lab_name

def lab(view_func):
    def _decorator(request, lab_name, *args, **kwargs):
        # process the lab_name argument
        process_lab_name(request, lab_name)
        # when calling the view function, exclude the lab_name argument
        response = view_func(request, *args, **kwargs)
        return response
    return wraps(view_func)(_decorator)

@lab
def some_view(request):
    return render(...)

你的路线看起来像url(r'^(?P<lab_name>\w+)/app'

关于python - 带有动态前缀的 Django URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27302866/

相关文章:

python 扭曲 : Is it possible to reload certificates on the fly?

python - 使用带有结构指针的 ctypes 调用函数

django - 使用django-storages和boto3在Django中调用CreateMultipartUpload操作时访问AccessDenied

python - 在 Django admin 中添加内联多对多对象

Django 按需创建/更改表

python - pandas read_sql。如何使用日期字段的where子句进行查询

python - pandas 对不规则间隔时间数据进行重新采样

python - 从 Django 连接到 MySQL

Django:为什么在外键定义中的模型周围有引号

python - Selenium 列表到 MySQL 数据库表中