python-geoip 在 python3.4 上不起作用?

python-geoip does not work on python3.4?

我能够让 geolite2 在 python2.7 上工作 - 但我需要 3.4。我在 link: http://pythonhosted.org/python-geoip/ 上找到了 2.7 的说明。还提供了代码片段。

pip install python-geoip
pip install python-geoip-geolite2
>>> from geoip import geolite2
>>> match = geolite2.lookup('17.0.0.1')
>>> match is not None
True

所以我很自然地将所有 pip 更改为 pip3 并安装在新的 VM 上。代码没有错误,但它不会从它们的数据库中循环和 return 值。

pip3 install python-geoip
pip3 install python-geoip-geolite2

在 2.7 VM 中,当我使用 3.4 时,我将 geoip 库指向 /usr/local/lib/python2.7/dist-packages - 也不走运。但是,它可以在同一个虚拟机上的 2.7 上运行。

我需要做什么才能让它在 3.4 上运行?

python-geoip不支持Python3,两年没更新了。虽然有一个pull request to add Python 3 support, I would not expect it to be merged and released any time soon. I would recommend using the official MaxMind geoip2 package代替。

要使用 maxmind 数据库:

安装:

maxminddb 
maxminddb-geolite

在您的代码中:

from geolite2 import geolite2

match = geolite2.reader()
geoip = match.get('xxx.xxx.xxx.xxx')

安装:

apt install python3-pip
pip3 install maxminddb 
pip3 install maxminddb-geolite2

使用示例:

#!/usr/bin/python3
# coding=utf-8

from geolite2 import geolite2

reader = geolite2.reader()

# google's ip
match = reader.get('172.217.16.163')
if match:
  # print(match)
  if 'country' in match:
    print(match['country']['iso_code'])
  else:
    print(match['continent']['code'])
else:
  print('') 

python-geoip python 3 支持(使用 pippip3 安装):

pip3 install python-geoip-python3

输出:

Collecting python-geoip-python3
  Downloading python_geoip_python3-1.3-py2.py3-none-any.whl (7.4 kB)
Installing collected packages: python-geoip-python3
Successfully installed python-geoip-python3-1.3

对于 geolite2:

pip3 install python-geoip-geolite2

输出:

Successfully built python-geoip-geolite2
Installing collected packages: python-geoip-geolite2
Successfully installed python-geoip-geolite2-2015.303

示例 test_geoip.py:

#!/usr/bin/env python3

import socket
from geoip import geolite2
import argparse
import json

# Setup commandline arguments
parser = argparse.ArgumentParser(description='Get IP Geolocation info')
parser.add_argument('--hostname', action="store", dest="hostname", required=True)

# Parse arguments
given_args = parser.parse_args()
hostname = given_args.hostname
ip_address = socket.gethostbyname(hostname)

print("IP address: {0}".format(ip_address))

match = geolite2.lookup(ip_address)

if match is not None:
    print('Country: ',match.country)
    print('Continent: ',match.continent)
    print('Time zone: ', match.timezone)
    print('Location: ', match.location)

运行:

python3 test_geoip.py --hostname=amazon.co.uk

输出:

IP address: 178.236.7.220
Country:  IE
Continent:  EU
Time zone:  Europe/Dublin
Location:  (53.3478, -6.2597)

运行 再一次:

python3 test_geoip.py --hostname=amazon.co.uk

输出:

IP address: 54.239.34.171
Country:  US
Continent:  NA
Time zone:  America/Los_Angeles
Location:  (47.6103, -122.3341)