用 GeoIP2 进行地理定位¶
The GeoIP2
object is a wrapper for the MaxMind geoip2 Python
library. [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 库更快的速度。
例如¶
以下是其用法的示例:
>>> 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 参考¶
GeoIP
对象不需要任何参数来使用默认设置。然而,至少 GEOIP_PATH
配置应该用你 GeoIP 数据集位置的路径来设置。以下初始化关键字可用于自定义任何默认配置。
关键字参数 | 描述 |
---|---|
path |
GeoIP 数据所在的基本目录或城市或国家数据文件(.mmdb )所在的完整路径。假设城市和国家数据集都在这个目录中;覆盖 GEOIP_PATH 配置。 |
cache |
打开 GeoIP 数据集时的缓存配置。可以是(0、1、2、4、8)的整数,分别对应于 MODE_AUTO 、MODE_MMAP_EXT 、MODE_MMAP 、GEOIP_INDEX_CACHE 和 MODE_MEMORY C API 配置。默认值为 0(MODE_AUTO )。 |
country |
GeoIP 国家数据文件的名称。默认值为 GeoLite2-Country.mmdb 。设置这个关键字会覆盖 GEOIP_COUNTRY 的配置。 |
city |
GeoIP 城市数据文件的名称。默认为 GeoLite2-City.mmdb 。设置这个关键字会覆盖 GEOIP_CITY 的配置。 |
方法¶
查询¶
All the following querying routines may take an instance of
IPv4Address
or IPv6Address
, a string IP
address, or a fully qualified domain name (FQDN). For example,
IPv4Address("205.186.163.125")
, "205.186.163.125"
, and
"djangoproject.com"
would all be valid query parameters.
返回给定查询的城市信息字典。字典中的一些值可能是未定义的(None
)。
返回给定查询的国家代码和国家的字典。
返回与查询对应的国家代码。
返回与查询对应的国家名称。