为我的站点设置geoip时出错"GeoIP路径必须是有效的文件或目录"

PK1*_*K10 3 python django

对于我的django应用程序,我试图通过amdin存储登录位置的日志.

我创建了一个中间件并尝试使用"django.contrib.gis.utils import GeoIP"来获取地理位置的纬度和经度值.

但得到的错误如下:

/ admin /的GeoIPException

GeoIP路径必须是有效的文件或目录.

代码:trackware.py

from django.contrib.gis.utils import GeoIP
from core.models import Log # your simple Log model

def get_ip(request):
   xff = request.META.get('HTTP_X_FORWARDED_FOR')
   if xff:
      return xff.split(',')[0]
   return request.META.get('REMOTE_ADDR')

class UserLocationLoggerMiddleware(object):

    def process_request(self, request):
        if request.user and request.user.is_superuser:
            # Only log requests for superusers,
            # you can control this by adding a setting
            # to track other user types
            ip = get_ip(request)
            g = GeoIP()
            lat,long = g.lat_lon(ip)
            Log.objects.create(request.user, ip, lat, long)
Run Code Online (Sandbox Code Playgroud)

我在settings.py中所做的更改:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',

#custom middleware
    'smartDNA.trackware.UserLocationLoggerMiddleware',
)

BASE_DIR = os.path.abspath(os.path.dirname(__file__))
GEOIP_PATH =os.path.join(BASE_DIR, 'geoip')
Run Code Online (Sandbox Code Playgroud)

models.py:

class Log(models.Model):
    user = models.CharField(verbose_name="User",max_length=32)
    ip=models.IPAddressField(verbose_name="IP")
    lat= models.DecimalField(verbose_name="Lat",max_digits=10,decimal_places=1)
    long= models.DecimalField(verbose_name="Long",max_digits=10,decimal_places=1)
Run Code Online (Sandbox Code Playgroud)

admin.py中注册模型:

admin.site.register(Log)
Run Code Online (Sandbox Code Playgroud)

我正在做的错误和解决方案是什么......

rsm*_*rsm 14

我遇到了同样的问题,我用这种方式解决了它:

这是我的项目..

> root
    > app
        settings.py
        urls.py
        ...
    > static
    > application
    > templates
    manage.py
Run Code Online (Sandbox Code Playgroud)

1)下载GeoLiteCountry和GeoLiteCity.dat.gz

2)在root中创建一个名为的文件夹geoip并将两个文件放在里面. 确保两个文件都重命名为GeoIPCity.dat和GeoIP.dat

3)在设置文件中指定路径 GEOIP_PATH = os.path.join(BASE_DIR, 'geoip')

4)做一个测试

python manage.py shell
>>> from django.contrib.gis.geoip import GeoIP
>>> g = GeoIP()
>>> g.city('72.14.207.99')
..
Run Code Online (Sandbox Code Playgroud)

如果它仍然无法工作,请查看g实例以找出指向位置:

>>> print g._city_file
/home/foo/root/geoip/GeoIPCity.dat
>>> print g._country_file
/home/foo/root/geoip/GeoIP.dat
Run Code Online (Sandbox Code Playgroud)

*如果你得到一个空字符串,试着找到bug.不要尝试通过修改实例重新分配路径g._city_file=/home/foo/Desktop/GeoIP.0.dat,它将无法正常工作!


Bur*_*lid 6

文档中

为了执行基于IP的地理定位,GeoIP对象需要GeoIP C库以及二进制格式的GeoIP国家或城市数据集(CSV文件将无法使用!)。这些数据集可以从MaxMind下载。抓取GeoLiteCountry / GeoIP.dat.gz和GeoLiteCity.dat.gz文件,并将其解压缩到与您在设置中设置GEOIP_PATH对应的目录中。

确保已完成上述操作,否则系统不知道如何将IP映射到位置。