Django:在中间件中用request.urlconf覆盖ROOT_URLCONF [英] Django: Overwrite ROOT_URLCONF with request.urlconf in middleware

查看:329
本文介绍了Django:在中间件中用request.urlconf覆盖ROOT_URLCONF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  from django.utils.cache import patch_vary_headers 

class SubdomainMiddleware:
def process_request(self,request):
path = request.get_full_path()
root_url = path.split('/')[1]
domain_parts = request.get_host()。split('。')

if(len(domain_parts)> 2):
subdomain = domain_parts [0]
if(subdomain.lower()=='www'):
subdomain =无
else:
subdomain =无

request.subdomain = subdomain
request.domain = domain

如果request.subdomain ==api:
request.urlconf =rest_api_example.urls。 api
else:
request.urlconf =rest_api_example.urls。

我尝试使用set_urlconf模块from django.core.urlresolve rs也不行。我在这里缺少一些东西?

解决方案

有趣的是,我使用set_urlconf模块和request.urlconf来设置url路径,现在它的工作!

从django.core.urlresolvers导入set_urlconf 
如果request.subdomain ==api:
set_urlconf(rest_api_example.urls.api)
request.urlconf =rest_api_example.urls.api
else:
set_urlconf(rest_api_example.urls.default)
请求.urlconf =rest_api_example.urls.default


I am trying to overwrite ROOT_URLCONF with another url when the request contains "api" subdomain and this is what I have so far.

from django.utils.cache import patch_vary_headers  

class SubdomainMiddleware:
  def process_request(self, request):
    path = request.get_full_path()  
    root_url = path.split('/')[1]
    domain_parts = request.get_host().split('.')

    if (len(domain_parts) > 2):
        subdomain = domain_parts[0]
        if (subdomain.lower() == 'www'):
            subdomain = None
    else:
        subdomain = None

    request.subdomain = subdomain 
    request.domain = domain

    if request.subdomain == "api":
        request.urlconf = "rest_api_example.urls.api"
    else:
        request.urlconf = "rest_api_example.urls.

I tried using set_urlconf module "from django.core.urlresolvers" too but it didn't work. Am I missing something here?

解决方案

Interestingly, I used set_urlconf module and request.urlconf to set url path and now it's working!

    from django.core.urlresolvers import set_urlconf
    if request.subdomain == "api":
        set_urlconf("rest_api_example.urls.api")
        request.urlconf = "rest_api_example.urls.api"
    else:
        set_urlconf("rest_api_example.urls.default")
        request.urlconf = "rest_api_example.urls.default"

这篇关于Django:在中间件中用request.urlconf覆盖ROOT_URLCONF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆