如何在django中获取用户IP地址?如何在django中获取用户的IP?我有这样的观点:# Create your viewsfrom django.contrib.gis.utils import GeoIPfrom django.template import RequestContextfrom django.shortcuts import render_to_responsedef home(request):
g = GeoIP()
client_ip = request.META['REMOTE_ADDR']
lat,long = g.lat_lon(client_ip)
return render_to_response('home_page_tmp.html',locals())但我得到这个错误:KeyError at /mypage/
'REMOTE_ADDR'
Request Method: GET Request URL: http://mywebsite.com/mypage/
Django Version: 1.2.4
Exception Type: KeyError
Exception Value:
'REMOTE_ADDR'
Exception Location: /mysite/homepage/views.py in home, line 9
Python Executable: /usr/bin/python Python Version: 2.6.6
Python Path: ['/mysite', '/usr/local/lib/python2.6/dist-packages/flup-1.0.2-py2.6.egg', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages', '/usr/lib/pymodules/python2.6']
Server time: Sun, 2 Jan 2011 20:42:50 -0600
3 回答
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
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
确保正确配置了反向代理(如果有)(例如,mod_rpaf
为Apache安装)。
注意:以上使用了第一项X-Forwarded-For
,但您可能想要使用最后一项(例如,在Heroku的情况下:在Heroku上获取客户端的真实IP地址)
然后将请求作为参数传递给它;
get_client_ip(request)
添加回答
举报
0/150
提交
取消