python 使用GeoIP

来源:互联网 发布:python 示例 编辑:程序博客网 时间:2024/06/16 11:07

官网地址:http://dev.maxmind.com/geoip/geoip2/geolite2/#Databases


ubuntu 下安装很简单:

1. 安装geoip的py 库

sudo pip install pygeoip

2 下载 GeoLiteCity.dat


使用:

import pygeoipgi = pygeoip.GeoIP('GeoLiteCity.dat', pygeoip.MEMORY_CACHE) location = gi.record_by_addr(8.8.8.8)
print location>>> {'city': '', 'region_name': '', 'area_code': 0, 'time_zone': '', 'dma_code': 0, 'metro_code': None, 'country_code3': 'USA', 'latitude': 38.0, 'postal_code': '', 'longitude': -97.0, 'country_code': 'US', 'country_name': 'United States', 'continent': 'NA'}


注意区域,geoip使用它自己的code来标示,官网提供一个 CSV file which maps our region codes to region names

列分别为 ISO country code, region code (FIPS or ISO), and the region name.,也就是前两列综合对应 区域名称。

这样就可以用 '%s_%s' % (country_code, region_code) 做key 来做根据csv来做一个字典来简单的做对应关系。


原创粉丝点击