Django:在中间件中用request.urlconf覆盖ROOT_URLCONF

时间:2015-06-19 01:31:00

标签: python django django-rest-framework django-urls django-middleware

当我的请求包含“api”子域时,我试图用另一个URL覆盖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 = 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.

我也试过使用set_urlconf模块“来自django.core.urlresolvers”,但它没有用。我在这里错过了什么吗?

2 个答案:

答案 0 :(得分:3)

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

    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"

答案 1 :(得分:1)

至于django中的很多东西,已有应用程序 - https://github.com/jezdez/django-hosts