如何在Python中使用多个Geoip2(MaxMind)数据库
在Python中同时使用多个MaxMind GeoIP2数据库的解决方案
直接通过初始化多个独立的geoip2.database.Reader实例,分别对应不同的GeoIP2数据库,即可实现对同一IP的多库查询,再将各库返回的字段整合为你需要的地理位置输出。
实现步骤与代码示例
- 先确保安装了
geoip2库:
pip install geoip2
- 多数据库查询与数据整合代码:
import geoip2.database def get_combined_geo_info(ip): # 初始化各数据库的阅读器(替换为你的数据库文件路径) with ( geoip2.database.Reader('./GeoIP2-City.mmdb') as city_reader, geoip2.database.Reader('./GeoIP2-ASN.mmdb') as asn_reader, geoip2.database.Reader('./GeoIP2-Country.mmdb') as country_reader ): combined_info = {} try: # 从城市库获取城市、经纬度等信息 city_res = city_reader.city(ip) combined_info.update({ 'city': city_res.city.name, 'country_name': city_res.country.name, 'latitude': city_res.location.latitude, 'longitude': city_res.location.longitude, 'postal_code': city_res.postal.code }) # 从ASN库获取自治系统信息 asn_res = asn_reader.asn(ip) combined_info.update({ 'asn_number': asn_res.autonomous_system_number, 'asn_org': asn_res.autonomous_system_organization }) # 从国家库补充国家代码(如果城市库的信息不够) country_res = country_reader.country(ip) combined_info['country_code'] = country_res.country.iso_code except geoip2.errors.AddressNotFoundError: combined_info['status'] = 'error' combined_info['message'] = '该IP未在数据库中匹配到记录' return combined_info # 测试使用 if __name__ == '__main__': test_ip = '1.1.1.1' result = get_combined_geo_info(test_ip) print(result)
关键注意事项
- 每个
Reader实例对应一个独立的数据库文件,确保文件路径正确,数据库文件需自行从MaxMind获取(免费的GeoLite2或付费的GeoIP2版本均可) - 使用
with上下文管理器可以自动关闭阅读器,避免资源泄漏,比手动调用close()更可靠 - 必须捕获
geoip2.errors.AddressNotFoundError异常,防止因IP无匹配记录导致脚本崩溃 - 可根据实际需求选择需要组合的数据库(比如只组合City和ASN,或添加ISP库等),按需提取字段即可
内容的提问来源于stack exchange,提问作者Kanzeon
相关产品推荐
相关产品推荐

