GeoIP2数据库——根据ip确定国家/地区,过滤某区域ip

GeoIP2下载:https://dev.maxmind.com/geoip/geoip2/downloadable/

GeoIP2数据库使用例子:

from django.conf import settings as django_settings
import geoip2.database

def get(self, request, **kwargs):
    if request.META.get('HTTP_X_FORWARDED_FOR'):
        ip = request.META['HTTP_X_FORWARDED_FOR']
    else:
        ip = request.META['REMOTE_ADDR']
    print(ip)
    ip = '128.101.101.101'

    DIR = os.path.join(str(django_settings.APPS_DIR), 'static', 'mmdb', 'GeoLite2-Country.mmdb')
    reader = geoip2.database.Reader(DIR)

    response = reader.country(ip_address=ip)
    print(response.country.name, '---', response.continent.name)
    if response.continent.name == 'Europe':
        raise Http404

你可能感兴趣的:(Python)