---
title: "用 GeoIP2 进行地理定位"
version: 3.2
locale: zh-hans
source: https://docs.djangoproject.com/zh-hans/3.2/ref/contrib/gis/geoip2/
canonical: https://djangodocs.dev/zh-hans/3.2/ref/contrib/gis/geoip2/
---
# 用 GeoIP2 进行地理定位

[`GeoIP2`](#django.contrib.gis.geoip2.GeoIP2) 对象是对 [MaxMind geoip2 Python 库](https://geoip2.readthedocs.io/) 的包装。[^1]

为了执行基于 IP 的地理定位， [`GeoIP2`](#django.contrib.gis.geoip2.GeoIP2) 对象需要 [geoip2 Python 库](https://pypi.org/project/geoip2/) 和二进制格式的 GeoIP `Country` 和／或 `City` [数据集](https://dev.maxmind.com/geoip/geolite2-free-geolocation-data) （CSV 文件将无法使用！）。抓取 `GeoLite2-Country.mmdb.gz` 和 `GeoLite2-City.mmdb.gz` 文件，并将其解压到与 [`GEOIP_PATH`](#std-setting-GEOIP_PATH) 配置对应的目录中。

另外，建议安装 [libmaxminddb C 库](https://github.com/maxmind/libmaxminddb/) ，这样 `geoip2` 就可以利用 C 库更快的速度。

## 例如

下面以其使用为例：

```
>>> 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 参考

#### `class GeoIP2(path=None, cache=0, country=None, city=None)`

`GeoIP` 对象不需要任何参数来使用默认设置。然而，至少 [`GEOIP_PATH`](#std-setting-GEOIP_PATH) 配置应该用你 GeoIP 数据集位置的路径来设置。以下初始化关键字可用于自定义任何默认配置。

| 关键字参数 | 描述 |
| --- | --- |
| `path` | GeoIP 数据所在的基本目录或城市或国家数据文件（`.mmdb`）所在的完整路径。假设城市和国家数据集都在这个目录中；覆盖 [`GEOIP_PATH`](#std-setting-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`](#std-setting-GEOIP_COUNTRY) 的配置。 |
| `city` | GeoIP 城市数据文件的名称。默认为 `GeoLite2-City.mmdb`。设置这个关键字会覆盖 [`GEOIP_CITY`](#std-setting-GEOIP_CITY) 的配置。 |

## 方法

### 实例化

#### `classmethod GeoIP2.open(path, cache)`

该类方法从给定的数据库路径和给定的缓存配置中实例化 GeoIP 对象。

### 查询

以下所有的查询程序可以采用一个字符串 IP 地址或一个完全限定域名（FQDN）。例如，`'205.186.163.125'` 和 `'djangoproject.com'` 都是有效的查询参数。

#### `GeoIP2.city(query)`

返回给定查询的城市信息字典。字典中的一些值可能是未定义的（`None`）。

#### `GeoIP2.country(query)`

返回给定查询的国家代码和国家的字典。

#### `GeoIP2.country_code(query)`

返回与查询对应的国家代码。

#### `GeoIP2.country_name(query)`

返回与查询对应的国家名称。

### 坐标检索

#### `GeoIP2.coords(query)`

返回 (经度, 纬度) 的坐标元组。

#### `GeoIP2.lon_lat(query)`

返回 (经度, 纬度) 的坐标元组。

#### `GeoIP2.lat_lon(query)`

返回 (经度, 纬度) 的坐标元组，

#### `GeoIP2.geos(query)`

返回与查询对应的 [`Point`](/zh-hans/3.2/ref/contrib/gis/geos/#django.contrib.gis.geos.Point) 对象。

## 配置

### `GEOIP_PATH`

字符串或 [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) 指定 GeoIP 数据文件所在的目录。除非在初始化 [`GeoIP2`](#django.contrib.gis.geoip2.GeoIP2) 对象时用 `path` 关键字手动指定，否则该配置是 *必须的*。

### `GEOIP_COUNTRY`

GeoIP 国家数据文件的基名。默认为 `'GeoLite2-Country.mmdb'`。

### `GEOIP_CITY`

GeoIP 城市数据文件的基名。默认为 `'GeoLite2-City.mmdb'`。

## 异常

#### `exception GeoIP2Exception`

当调用底层的 `geoip2` 库时发生错误而引发的异常。

**脚注**

[^1]: GeoIP(R) 是 MaxMind, Inc 的注册商标。
