如何在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

当前回答

Alexander的回答很好,但是缺少对代理的处理,代理有时会在HTTP_X_FORWARDED_FOR报头中返回多个IP。

真实IP通常在列表的末尾,如下所示:http://en.wikipedia.org/wiki/X-Forwarded-For

解决方案是对Alexander的代码进行简单的修改:

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1].strip()
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

其他回答

在Django的最新版本中,清楚地提到 客户端的Ip地址为

request.META.get("REMOTE_ADDR")

更多信息请查看Django文档

Alexander的回答很好,但是缺少对代理的处理,代理有时会在HTTP_X_FORWARDED_FOR报头中返回多个IP。

真实IP通常在列表的末尾,如下所示:http://en.wikipedia.org/wiki/X-Forwarded-For

解决方案是对Alexander的代码进行简单的修改:

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1].strip()
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

最简单的解决方案(如果你正在使用fastcgi+nignx)是itgorilla评论的:

谢谢你这个好问题。我的fastcgi没有传递REMOTE_ADDR元键。我在nginx.conf中添加了下面的行,并修复了这个问题:——itgorilla

Ps:我添加这个答案只是为了让他的解决方案更明显。

使用下面的函数获取ip地址:

def get_ip_address(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

在此之后,您可以从web应用程序http://www.iplocinfo.com/:获得用户位置数据和其他信息

import requests
def get_ip_data(request):
    ip_address = get_ip_address(request)
    api_key = "your api key"
    endPoint = f'https://www.iplocinfo.com/api/v1/{ip_address}?apiKey={api_key}'
    data = requests.get(endPoint)
    return data.json()

在获得ip地址后,您需要找到位置

# pip install geocoder

import geocoder

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]
        ip_location = geocoder.ip(f"{ip}")
        ip_location = geocoder.ip("me")
        print(ip_location.city)
        # you can get city such as "New York"
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip