mas*_*nyo 5 python django django-middleware django-urls django-rest-framework
当请求包含“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.
Run Code Online (Sandbox Code Playgroud)
我也尝试使用 set_urlconf 模块“来自 django.core.urlresolvers”,但它不起作用。我在这里错过了什么吗?
有趣的是,我使用 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"
Run Code Online (Sandbox Code Playgroud)