gpt4 book ai didi

python - 如何在 Django 中获取用户 IP 地址?

转载 作者:IT老高 更新时间:2023-10-28 12:10:19 33 4
gpt4 key购买 nike

我如何在 Django 中获取用户的 IP?

我有这样的看法:

# Create your views
from django.contrib.gis.utils import GeoIP
from django.template import RequestContext
from django.shortcuts import render_to_response

def 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.example/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

最佳答案

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

确保您已正确配置反向代理(如果有)(例如为 Apache 安装了 mod_rpaf)。

注意:上面使用 X-Forwarded-For 中的 first 项,但您可能希望使用 last 项(例如, 对于 Heroku: Get client's real IP address on Heroku )

然后将请求作为参数传递给它;

get_client_ip(request)

Django documentation for HttpRequest.META

关于python - 如何在 Django 中获取用户 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4581789/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com