用 GeoIP2 进行地理定位Link to this heading
GeoIP2 对象是对 MaxMind geoip2 Python 库 的包装。[1]
为了执行基于 IP 的地理定位, GeoIP2 对象需要 geoip2 Python 库 和二进制格式的 GeoIP Country 和/或 City 数据集 (CSV 文件将无法使用!)。抓取 GeoLite2-Country.mmdb.gz 和 GeoLite2-City.mmdb.gz 文件,并将其解压到与 GEOIP_PATH 配置对应的目录中。
另外,建议安装 libmaxminddb C 库 ,这样 geoip2 就可以利用 C 库更快的速度。
例如Link to this heading
下面以其使用为例:
>>> from django.contrib.gis.geoip2 import GeoIP2
>>> g = GeoIP2()
>>> g.country('google.com')
{'country_code': 'US', 'country_name': 'United States'}
>>> g.city('72.14.207.99')
{'city': 'Mountain View',
'continent_code': 'NA',
'continent_name': 'North America',
'country_code': 'US',
'country_name': 'United States',
'dma_code': 807,
'is_in_european_union': False,
'latitude': 37.419200897216797,
'longitude': -122.05740356445312,
'postal_code': '94043',
'region': 'CA',
'time_zone': 'America/Los_Angeles'}
>>> g.lat_lon('salon.com')
(39.0437, -77.4875)
>>> g.lon_lat('uh.edu')
(-95.4342, 29.834)
>>> g.geos('24.124.1.80').wkt
'POINT (-97 38)'
API 参考Link to this heading
- class GeoIP2(path=None, cache=0, country=None, city=None)Link to this definition
GeoIP 对象不需要任何参数来使用默认设置。然而,至少 GEOIP_PATH 配置应该用你 GeoIP 数据集位置的路径来设置。以下初始化关键字可用于自定义任何默认配置。
关键字参数 |
描述 |
|---|---|
|
GeoIP 数据所在的基本目录或城市或国家数据文件( |
|
打开 GeoIP 数据集时的缓存配置。可以是(0、1、2、4、8)的整数,分别对应于 |
|
GeoIP 国家数据文件的名称。默认值为 |
|
GeoIP 城市数据文件的名称。默认为 |
方法Link to this heading
实例化Link to this heading
- classmethod GeoIP2.open(path, cache)Link to this definition
该类方法从给定的数据库路径和给定的缓存配置中实例化 GeoIP 对象。
查询Link to this heading
以下所有的查询程序可以采用一个字符串 IP 地址或一个完全限定域名(FQDN)。例如,'205.186.163.125' 和 'djangoproject.com' 都是有效的查询参数。
- GeoIP2.city(query)Link to this definition
返回给定查询的城市信息字典。字典中的一些值可能是未定义的(None)。
- GeoIP2.country(query)Link to this definition
返回给定查询的国家代码和国家的字典。
- GeoIP2.country_code(query)Link to this definition
返回与查询对应的国家代码。
- GeoIP2.country_name(query)Link to this definition
返回与查询对应的国家名称。
坐标检索Link to this heading
- GeoIP2.coords(query)Link to this definition
返回 (经度, 纬度) 的坐标元组。
- GeoIP2.lon_lat(query)Link to this definition
返回 (经度, 纬度) 的坐标元组。
- GeoIP2.lat_lon(query)Link to this definition
返回 (经度, 纬度) 的坐标元组,
- GeoIP2.geos(query)Link to this definition
返回与查询对应的 Point 对象。
配置Link to this heading
GEOIP_PATHLink to this heading
字符串或 pathlib.Path 指定 GeoIP 数据文件所在的目录。除非在初始化 GeoIP2 对象时用 path 关键字手动指定,否则该配置是 必须的。
GEOIP_COUNTRYLink to this heading
GeoIP 国家数据文件的基名。默认为 'GeoLite2-Country.mmdb'。
GEOIP_CITYLink to this heading
GeoIP 城市数据文件的基名。默认为 'GeoLite2-City.mmdb'。
异常Link to this heading
- exception GeoIP2ExceptionLink to this definition
当调用底层的
geoip2库时发生错误而引发的异常。
脚注