How to get hostname or IP in settings.py so that i can use it to decide which app's urls to use

拥有回忆 提交于 2019-12-08 07:53:15

问题


I am making a django application where it will have 2 apps. When you open www.webName.co.id it will use urls.py from app A, but when you open webName.co.uk it will use urls.py from app B

This is the urls.py from the main project:

urlpatterns = [
  url(r'^tinymce/', include('tinymce.urls')),
  url(r'^filer/', include('filer.urls')),
  url(r'^ckeditor/', include('ckeditor_uploader.urls')),
  url(r'^admin/', admin.site.urls),
]

I was planning to add something like this to that file:

if settings.CURRENT_HOST_IP == 'www.webname.co.id':
    urlpatterns += url(r'^', include('webname_id.urls')),
else:
    urlpatterns += url(r'^', include('webname_uk.urls')),

That way, it will simply use the urls from the app that is being used, depending on the current www you are entering the site with.

So my project have 1 backend admin, but multiple front-end templates and urls. The problem is i can't figure out how to set CURRENT_HOST_IP in the settings.py,

Usually i use this to get the current IP / host the user is using:

 request.META['HTTP_HOST']

But i can't access the request object in settings, is there any way in Python (not django) to get the www / IP address / hostname that i typed in the browser?


回答1:


You need two alternative urlconf files in your main project:

# project/project/urls_id.py

from django.conf.urls import url

from urls import urlpatterns

urlpatterns.append(url(r'^', include 'webname_id.urls'))
# project/project/urls_uk.py

from django.conf.urls import url

from urls import urlpatterns

urlpatterns.append(url(r'^', include 'webname_uk.urls'))

In your middleware, select the appropriate urlconf based on the host.

class YourMiddleware(object):

    # For Django 1.10+

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        if request.get_host() == 'www.webname.co.id':
            request.urlconf = 'project.urls_id'
        else:
            request.urlconf = 'project.urls_uk'

        response = self.get_response(request)

        return response


来源:https://stackoverflow.com/questions/44001085/how-to-get-hostname-or-ip-in-settings-py-so-that-i-can-use-it-to-decide-which-ap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!