星期四, 10月 31, 2019

從 IP 取得 Country / City / 經緯度

使用的環境是 Ubuntu 16.04 + Django 2.2,先處理 geoip 資料庫。
sudo apt-get install geoipupdate
安裝完以後先填設定,編輯 /etc/GeoIP.conf ,這邊要注意 geoipupdate 版本,2.5 之前的話,AccountID 要改成 UserId,EditionIDs 要改成 ProductIds ,Ubuntu 16.04 用的是 2.5 之前的版本:
# The following AccountID and LicenseKey are required placeholders.
# For geoipupdate versions earlier than 2.5.0, use UserId here instead of AccountID.
# AccountID 0
UserId 0
LicenseKey 000000000000


# Include one or more of the following edition IDs:
# * GeoLite2-City - GeoLite 2 City
# * GeoLite2-Country - GeoLite2 Country
# For geoipupdate versions earlier than 2.5.0, use ProductIds here instead of EditionIDs.
# EditionIDs GeoLite2-City GeoLite2-Country
ProductIds GeoLite2-City GeoLite2-Country
執行 sudo -H geoipupdate,檔案會下載到 /var/lib/GeoIP
接著在 Django 環境下安裝 geoip2
pip install geoip2
然後先在 shell 裡試試看:python manage.py shell
from django.contrib.gis.geoip2 import GeoIP2
g = GeoIP2('/var/lib/GeoIP')  # 將路徑指過去
print(g.country('59.120.21.9'))
print(g.city('59.120.21.9'))
print(g.lat_lon('59.120.21.9'))
一般來說,用 city(“your_ip”) 就可以拿到足夠的資訊了
{'city': 'Taipei',
 'continent_code': 'AS',
 'continent_name': 'Asia',
 'country_code': 'TW',
 'country_name': 'Taiwan',
 'dma_code': None,
 'latitude': 25.0478,
 'longitude': 121.5318,
 'postal_code': None,
 'region': 'TPE',
 'time_zone': 'Asia/Taipei'}
參考資料

沒有留言: