我希望通过检测用户IP地址来将我的用户重定向到网站的特定位置区域。
在 Django 1.1.1 下,最好的实现方式是什么?
谢谢。
编辑:我想要基于欧洲的城市进行定位。
我希望通过检测用户IP地址来将我的用户重定向到网站的特定位置区域。
在 Django 1.1.1 下,最好的实现方式是什么?
谢谢。
编辑:我想要基于欧洲的城市进行定位。
虽然已经提到了GeoIP,但我发现pygeoip更容易安装,如果你想将其嵌入应用程序而不是安装在Python的site-packages中,它就是最佳选择。尽管如此,它仍能与免费的MaxMind数据库(例如GeoLite City)完美配合使用。
使用示例(与GeoIP几乎相同):
>>> import pygeoip
>>> gi = pygeoip.GeoIP(GEOIP_DATABASE, pygeoip.GEOIP_STANDARD)
>>> gi.record_by_addr(ip)
{'country': '...', 'country_code': '...', ...}
from urllib2 import urlopen, Request
import re, socket
from django.conf import settings
domain_re = re.compile('^(http|https):\/\/?([^\/]+)')
domain = domain_re.match(settings.SITE_URL).group(2)
def getUserCountry(ip):
url = "http://api.wipmania.com/" + ip + "?" + domain
socket.setdefaulttimeout(5)
headers = {'Typ':'django','Ver':'1.1.1','Connection':'Close'}
try:
req = Request(url, None, headers)
urlfile = urlopen(req)
land = urlfile.read()
urlfile.close()
return land[:2]
except Exception:
return "XX"
基于一些免费服务。
虽然速度不快,但您可以添加更多的免费服务:
设置:
IPCOUNTRY_APYKEY = [
{# free tier 2 querys per second
"url": "http://api.ipinfodb.com/v3/ip-country/?ip={ip}&key={key}&format=json",
"params": {
"key": "*****************************",
},
"fieldname": "countryCode",
},
{# free tier 150 querys per minute and https is not suported in free tier
"url": "http://ip-api.com/json/{ip}?fields=2",
"params": {},
"fieldname": "countryCode",
},
{# free tier 1.500 queries per day
"url": "https://api.ipdata.co/{ip}?api-key={key}",
"params": {
"key": "*****************************",
},
"fieldname": "country_code",
},
{# free tier 10.000 queries per month and https is not suported in free tier
"url": "http://api.ipstack.com/{ip}?access_key={key}",
"params": {
"key": "*****************************",
},
"fieldname": "country_code",
},
{# free tier 10.000 queries per month and https is not suported in free tier
"url": "http://api.ipapi.com/{ip}?access_key={key}",
"params": {
"key": "*****************************",
},
"fieldname": "country_code",
},
]
代码:
import json
import urllib3
from django.conf import settings
for service in settings.IPCOUNTRY_APYKEY:
url = service["url"].format(ip=ip,**service["params"])
headers = {'Type': 'django', 'Ver': '1.1.1', 'Connection': 'Close'}
urllib3.disable_warnings()
http_call = urllib3.PoolManager()
try:
r = http_call.request('GET', url, headers=headers, timeout=1.0)
if r.status == 200:
json_response = json.loads(r.data.decode("utf-8"))
print(json_response[service["fieldname"]])
except Exception as e:
pass
return None
def redirect_based_on_ip(request):
ip = request.meta['REMOTE_ADDR']
if ip == SOMETHING:
return HttpResponseRedirect('/something')
elif ip == SOMETHING_ELSE:
return HttpResponseRedirect('/something_else')
# ...
您可以通过使用IP2Location Python库和IP2Location BIN数据库来实现此目的。首先,从https://www.ip2location.com/database/ip2location购买商业IP2Location数据库或从https://lite.ip2location.com/下载免费的IP2Location LITE数据库。然后,使用以下命令安装IP2Location Python库:pip install IP2Location
安装完成后,打开您的views.py文件并将以下代码添加到文件中:
from django.http import HttpResponse
from django.shortcuts import redirect
import IP2Location
database = IP2Location.IP2Location(YOUR_DATABASE_PATH)
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')
if ip == '127.0.0.1': # Only define the IP if you are testing on localhost.
ip = '8.8.8.8'
return ip
def redirect_view(request):
ip = get_client_ip(request)
rec = database.get_all(ip)
if rec.city == 'London': # Or any other city name
response = redirect('PATH_REDIRECT_TO')
return response
def redirectsucess_view(request):
return HttpResponse('Welcome!')
接下来,打开 urls.py 文件,在 urlpatterns 列表中添加以下代码:
path('redirect/', views.redirect_view),
path('PATH_REDIRECT_TO/', views.redirectsucess_view)
我已经制作了一个SO 答案,其中我使用了Cloudflare CDN,他们提供了每个访问者的GEO位置的额外头部信息。优点是我们不需要安装任何外部库或进行任何API调用。重定向可以通过Django中间件实现。