【发布时间】:2014-08-17 12:58:53
【问题描述】:
Django 1.4 + python2.7
我有一个网站,它有三个域,比如说india.abc.com、usa.abc.com 和intl.abc.com。
现在我想要的是基于 IP 地址来重定向域。假设用户属于印度(IP 地址),他/她应该去india.abc.com,如果用户在美国,他/她应该去usa.abc.com。
请指教。最好的方法是什么?
【问题讨论】:
标签: django
Django 1.4 + python2.7
我有一个网站,它有三个域,比如说india.abc.com、usa.abc.com 和intl.abc.com。
现在我想要的是基于 IP 地址来重定向域。假设用户属于印度(IP 地址),他/她应该去india.abc.com,如果用户在美国,他/她应该去usa.abc.com。
请指教。最好的方法是什么?
【问题讨论】:
标签: django
首先你需要一个IP to LOCATION服务来获取IP对应的位置。只要您拥有该服务(或基于数据库的查找算法),您就可以这样做:
# got from here: http://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def get_ip_location(ip):
# here you need to invoke a IP to location service, or implement your own.
# It's not that hard. Start here: http://stackoverflow.com/questions/4179000/best-way-to-detect-country-location-of-visitor
pass
def index(request):
ip = get_client_ip(request)
location = get_ip_location(ip)
if location == 'usa':
return redirect('http://usa.abc.com')
elif location == 'japan':
return redirect('http://jpn.abc.com')
# you get the idea
else:
return redirect('http://global.abc.com')
【讨论】: