用 GeoIP2 进行地理定位Link to this heading
GeoIP2 对象是 MaxMind geoip2 Python 库 的包装器。[1]
为了执行基于 IP 的地理定位,GeoIP2 对象需要 geoip2 Python 包以及以二进制格式提供的 GeoIP Country 和/或 City 数据集(CSV 文件将不起作用!),可以从 MaxMind 或 DB-IP 等网站下载。获取 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")
{'continent_code': 'NA',
'continent_name': 'North America',
'country_code': 'US',
'country_name': 'United States',
'is_in_european_union': False}
>>> g.city("72.14.207.99")
{'accuracy_radius': 1000,
'city': 'Mountain View',
'continent_code': 'NA',
'continent_name': 'North America',
'country_code': 'US',
'country_name': 'United States',
'is_in_european_union': False,
'latitude': 37.419200897216797,
'longitude': -122.05740356445312,
'metro_code': 807,
'postal_code': '94043',
'region_code': 'CA',
'region_name': 'California',
'time_zone': 'America/Los_Angeles',
'dma_code': 807,
'region': 'CA'}
>>> 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
以下所有查询例程都可以接受 IPv4Address 或 IPv6Address 的实例、字符串 IP 地址或完全限定域名 (FQDN)。例如,IPv4Address("205.186.163.125")、"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包装器中发生错误时引发的异常。来自底层geoip2库的异常会原样传递。
脚注