gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:13:43 27 4
gpt4 key购买 nike

对于我的 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)

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

模型.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 重新分配路径,这是行不通的!

关于python - 为我的站点设置 geoip 时出错 "GeoIP path must be a valid file or directory",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20853551/

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