【Python】使用geoip2数据库来实现一个离线的IP查询方法

下载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)

运行截图
在这里插入图片描述

  • 14
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在ThinkPHP项目中使用GeoIP2来实现限制请求IP只能巴西访问,你可以按照以下步骤进行配置: 1. 安装GeoIP2依赖包:在命令行中,进入你的ThinkPHP项目目录,然后运行以下命令来安装GeoIP2依赖包: ```shell composer require geoip2/geoip2:~2.0 ``` 2. 下载GeoIP2数据库:访问MaxMind网站(https://dev.maxmind.com/geoip/geoip2/geolite2/),下载GeoIP2数据库文件(通常是以.mmdb扩展名结尾的文件)。 3. 将GeoIP2数据库文件放置在项目的合适位置,例如`public`文件夹下的`geoip`文件夹。 4. 在ThinkPHP项目中创建一个新的中间件(Middleware),用于检查请求IP是否为巴西的IP。在命令行中,进入你的ThinkPHP项目目录,然后运行以下命令来创建中间件: ```shell php think make:middleware BrazilIPCheck ``` 5. 编辑刚创建的中间件文件:在`app/middleware`目录下找到并打开`BrazilIPCheck.php`文件。 6. 在`handle`方法中,添加以下代码来检查请求IP是否为巴西的IP: ```php use GeoIp2\Database\Reader; public function handle($request, \Closure $next) { $ip = $request->ip(); // 加载GeoIP2数据库 $databasePath = public_path('geoip/GeoLite2-Country.mmdb'); $reader = new Reader($databasePath); try { // 获取请求IP的国家信息 $record = $reader->country($ip); $countryCode = $record->country->isoCode; // 如果不是巴西的IP,则返回403 Forbidden 错误 if ($countryCode !== 'BR') { return response('403 Forbidden', 403); } } catch (\Exception $e) { // 处理数据库加载或查询错误 return response('500 Internal Server Error', 500); } return $next($request); } ``` 7. 保存并关闭`BrazilIPCheck.php`文件。 8. 在`app/middleware`目录下的`middleware.php`文件中,注册刚创建的中间件: ```php return [ // ... \app\middleware\BrazilIPCheck::class, // ... ]; ``` 9. 现在,所有请求将通过中间件进行处理,如果请求IP不是巴西的IP,将返回403 Forbidden 错误。 请注意,以上步骤仅适用于限制请求IP只能巴西访问。如果需要更复杂的访问控制和安全性,建议结合其他认证和授权机制来实现

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值