下载GeoLite2-City.mmdb数据库
点击GeoLite2-City下载
代码实现
注意:GeoLite2数据库文件放到py文件同级目录下即可
# -*- coding:utf-8 _*_
"""
@Project : Qingyuing-Server
@File : ip_query.py
@Author : 晴天
@CreateTime : 2023-12-29 10:43
"""
import os
import pprint
import geoip2.database
def query_ip_location(ip_address, locales='zh-CN'):
"""
查询IP地址的地理位置信息
:param ip_address: IP地址
:param locales: 国际化(如果locales不指定的话会默认输出英文我这里指定了中文)
:return: 返回IP信息
"""
db_path = os.path.dirname(__file__) + '/GeoLite2-City.mmdb'
if not os.path.exists(db_path):
raise FileNotFoundError('GeoLite2-City数据库不存在')
try:
with geoip2.database.Reader(db_path, locales=[locales]) as reader:
response = reader.city(ip_address)
location_info = {
'country_name': response.country.name, # 国家名称,中文显示
'country_iso_code': response.country.iso_code, # 国家ISO代码
'province_name': response.subdivisions.most_specific.name, # 省份名称,中文显示
'province_iso_code': response.subdivisions.most_specific.iso_code, # 省份ISO代码
'city_name': response.city.name, # 城市名称,中文显示
'postal_code': response.postal.code, # 邮政编码
'latitude': response.location.latitude, # 纬度
'longitude': response.location.longitude, # 经度
'time_zone': response.location.time_zone, # 时区
'continent_name': response.continent.name, # 大陆名称,中文显示
'continent_code': response.continent.code # 大陆代码
}
return location_info
except Exception as e:
print(f"查询IP地址时发生错误: {e}")
return {}
if __name__ == '__main__':
# 使用示例
ip = '113.68.255.182'
ip_info = query_ip_location(ip)
pprint.pprint(ip_info)
运行截图