> For the complete documentation index, see [llms.txt](https://close.gitbook.io/yun-wei-bi-ji/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://close.gitbook.io/yun-wei-bi-ji/python/flask/liu-da-jian-cha-xun-ip-di-zhi-jie-kou.md).

# 六、搭建查询IP地址接口

```python
pipenv install geoip2 flask
```

{% hint style="info" %}
这个库是为了将IP地址翻译成具体的地址信息

下载需要注册... URL: <https://www.maxmind.com/en/accounts/current/people/current>
{% endhint %}

```bash
(test001) [root@k3s-master test001]# tree 
.
├── app.py
├── GeoLite2-City.mmdb
├── Pipfile
└── Pipfile.lock
```

**app.py**

```bash
from flask import Flask, jsonify, request
import geoip2.database


app = Flask(__name__)

app.debug = False


@app.route('/', methods=['GET'])
def index():
  if 'ip' in request.args:
    ip = request.args.get('ip')
  else:
    ip = request.remote_addr

  try:
    reader  = geoip2.database.Reader(r'./GeoLite2-City.mmdb')
    response = reader.city(ip)
    iso_code = response.country.iso_code
    country = response.country.name
    city = response.city.name
    reader.close()
    result = {'code': 200,'msg': 'success','iso_code': iso_code, 'country': country, 'city':city}
  except:
    result = {'code': 400, 'msg': 'not found'}
  return jsonify(result)

if __name__ == '__main__':
  app.run()
```

```bash
python3 app.py
```

```bash

[root@k3s-master ~]# curl 127.0.0.1:5000/?ip=156.255.3.xx
{"city":"Central","code":200,"country":"Hong Kong","iso_code":"HK","msg":"success"}


[root@k3s-master ~]# curl 127.0.0.1:5000/?ip=220.181.38.148
{"city":null,"code":200,"country":"China","iso_code":"CN","msg":"success"}
```
