使用django GeoIP和MaxMind数据库

时间:2022-10-30 23:11:54

I'm trying to setup geoip in Django to identify the source of a connection (to tailor content for different countries) but running into a problem.

我正在尝试在Django中设置geoip以确定连接的来源(为不同国家量身定制内容)但遇到问题。

First I execute:

首先我执行:

from django.contrib.gis import geoip
geo = geoip.GeoIP('path to maxmind db')

Then geo.country('www.google.com') returns the US as you'd expect. Other popular websites also work fine.

然后geo.country('www.google.com')按照您的预期返回美国。其他热门网站也可以正常使用。

However when I try it on my own client IP I get an empty record. For example: geo.country('127.6.89.129')

但是,当我在我自己的客户端IP上尝试它时,我得到一个空记录。例如:geo.country('127.6.89.129')

returns {'country_name': None, 'country': None}

返回{'country_name':无,'国家':无}

What am I missing here? Does the maxmind database only cover popular sites so can't be used if I want to identify the source of the connection?

我在这里想念的是什么? maxmind数据库是否仅覆盖热门站点,因此如果我想识别连接源,则无法使用它?

I'm also using the browser locale settings to identify language but unfortunately I need geo-location to tailor some of the content independently of language.

我也使用浏览器区域设置来识别语言,但不幸的是我需要地理位置来定制一些独立于语言的内容。

2 个解决方案

#1


3  

Your ip could be forwarded

您的IP可以转发

def foo(request):  
    g = GeoIP()
    country = g.country(get_client_ip(request))
    country_code = country['country_code']


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

#2


4  

The IP address you used in the example is a local IP address, you cannot use it outside your network, did you try with a real public IP address?

您在示例中使用的IP地址是本地IP地址,您不能在网络外使用它,是否尝试使用真实的公共IP地址?

#1


3  

Your ip could be forwarded

您的IP可以转发

def foo(request):  
    g = GeoIP()
    country = g.country(get_client_ip(request))
    country_code = country['country_code']


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

#2


4  

The IP address you used in the example is a local IP address, you cannot use it outside your network, did you try with a real public IP address?

您在示例中使用的IP地址是本地IP地址,您不能在网络外使用它,是否尝试使用真实的公共IP地址?