5

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?

masanorinyo
  • 1,098
  • 2
  • 12
  • 25

2 Answers2

3

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"
masanorinyo
  • 1,098
  • 2
  • 12
  • 25
  • 1
    That's interesting, `set_urlconf()` _should_ not be necessary, as Django does that [here](https://github.com/django/django/blob/master/django/core/handlers/base.py#L131). Do you have some more details about why it "didn't work"? – knbk Jun 19 '15 at 10:27
  • 1
    i've been investigating why set_urlconf() did the trick but I still don't know why it worked. Once I figure it out, I will update my answer. – masanorinyo Jun 19 '15 at 18:47
  • @masanorinyo can i load the urls without a file? – Mickey Cheong Dec 26 '18 at 15:19
  • This answer is quite stale. I am on Django 2.2 now and just setting `urlconf` seems to work fine. Also, `set_urlconf` is now in `django.urls` but I dont' seem to need it. – Scott Stafford Jan 22 '20 at 19:34
1

As for many things in django, there is already the app for that - https://github.com/jezdez/django-hosts

kmmbvnr
  • 5,863
  • 4
  • 35
  • 44
  • And yes, you have to call `set_urlconf` and assign `request.urlconf ` elsewhere due crazy caching urlconf internals it will not works. – kmmbvnr Jun 19 '15 at 07:09