的 GeoIP2 对象是 MaxMind geoip2 Python library . [1]
为了执行基于IP的地理位置, GeoIP2 对象需要使用 geoip2 Python包和GeoIP Country and/or City datasets in binary format (the CSV files will not work!), downloaded from e.g. `MaxMind`__ 或 `DB-IP`__ 网站。抓起 GeoLite2-Country.mmdb.gz 和 GeoLite2-City.mmdb.gz 文件并将其解压缩到与 GEOIP_PATH 布景。
此外,建议安装 `libmaxminddb C library`_ 所以 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)'
这个 GeoIP 对象不需要任何参数即可使用默认设置。然而,至少 GEOIP_PATH 应使用地理IP数据集位置的路径设置设置设置。以下初始化关键字可用于自定义任何默认值。
关键字参数 |
描述 |
|---|---|
|
geoip数据所在的基本目录或城市或国家数据文件所在的完整路径 ( |
|
打开geoip数据集时的缓存设置。可以是(0,1,2,4,8)中对应于 |
|
geoip国家数据文件的名称。默认为 |
|
geoip城市数据文件的名称。默认为 |
以下所有查询例程都可以采用 IPv4Address 或 IPv6Address 、字符串IP地址或完全限定的域名(FQDN)。例如, IPv4Address("205.186.163.125") , "205.186.163.125" ,以及 "djangoproject.com" 都是有效的查询参数。
返回给定查询的城市信息字典。字典中的某些值可能未定义 (None )
返回具有给定查询的国家/地区代码和国家/地区的字典。
返回与查询对应的国家/地区代码。
返回与查询对应的国家/地区名称。
返回(经度、纬度)的坐标元组。
返回(纬度、经度)的坐标元组,
返回A Point 与查询对应的对象。
GEOIP_PATH¶字符串或 pathlib.Path 指定GeoIP数据文件所在的目录。此设置 required 除非手动指定 path 初始化时关键字 GeoIP2 对象。
GEOIP_COUNTRY¶用于geoip国家数据文件的基名称。默认为 'GeoLite2-Country.mmdb' .
GEOIP_CITY¶用于geoip city数据文件的基名称。默认为 'GeoLite2-City.mmdb' .
脚注
5月 28, 2025