为我的网站设置 geoip 时出错 "GeoIP path must be a valid file or directory"



对于我的django应用程序,我正在尝试通过amdin存储登录位置的日志。

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

但是得到错误如下:

GeoIPException at/admin/

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)

我在 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')

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)

在 admin.py 中注册模型:

admin.site.register(Log)

我正在做的错误是什么,请解决....

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

这是我的项目..

> root
    > app
        settings.py
        urls.py
        ...
    > static
    > application
    > templates
    manage.py

1)下载GeoLiteCountry和GeoLiteCity.dat.gz

2)在根目录中创建一个名为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')
..

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

>>> print g._city_file
/home/foo/root/geoip/GeoIPCity.dat
>>> print g._country_file
/home/foo/root/geoip/GeoIP.dat

*如果您得到一个空字符串,请尝试查找错误。不要尝试要通过修改实例g._city_file=/home/foo/Desktop/GeoIP.0.dat来重新分配路径,行不通!

从文档中:

为了执行基于 IP 的地理位置,GeoIP 对象需要 GeoIP C 库和 GeoIP 国家或城市数据集 二进制格式(CSV 文件将不起作用!这些数据集可能是 从MaxMind下载。获取GeoLiteCountry/GeoIP.dat.gz和 GeoLiteCity.dat.gz文件并将它们解压缩到相应的目录中 到您在设置中设置GEOIP_PATH的内容。

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

我已经改变了这个

GEOIP_PATH =os.path.join(BASE_DIR, 'geoip')

GEOIP_PATH =os.path.join(BASE_DIR, 'geoip/')

我遇到了类似的问题,然后我改变了

GEOIP_PATH =os.path.join(BASE_DIR, 'geoip')GEOIP_PATH =os.path.join('geoip') .

希望对您有所帮助。

相关内容

最新更新