diff --git a/src/common/utils/ip.py b/src/common/utils/ip.py index 039ee66..5bbf50f 100644 --- a/src/common/utils/ip.py +++ b/src/common/utils/ip.py @@ -2,14 +2,13 @@ IP地址工具模块 ============================================================= -提供客户端IP获取和地理位置查询: -- get_client_ip: 获取客户端真实IP(需配合Flask ProxyFix使用) -- get_ip_location: 调用第三方API查询IP地理位置 +提供客户端IP获取功能: +- get_client_ip: 获取客户端真实IP(支持反向代理场景) + +地理位置查询请使用 ip2region 模块(离线数据库,高性能)。 """ -import json import logging -import urllib.request logger = logging.getLogger(__name__) @@ -18,38 +17,28 @@ def get_client_ip(): """ 获取客户端真实IP地址 - 通过Flask ProxyFix中间件由PROXY_NUM配置自动设置 - request.remote_addr为真实客户端IP。未配置ProxyFix时, - request.remote_addr即为直连IP,避免客户端伪造。 + 优先级: + 1. X-Forwarded-For 头(反向代理场景,取第一个非内网IP) + 2. X-Real-IP 头(Nginx 常用配置) + 3. remote_addr(直连场景) Returns: str: 客户端IP地址 """ from flask import request + # 优先从 X-Forwarded-For 获取(反向代理场景) + forwarded_for = request.headers.get("X-Forwarded-For", "") + if forwarded_for: + # 格式: client, proxy1, proxy2 → 取第一个 + first_ip = forwarded_for.split(",")[0].strip() + if first_ip and first_ip not in ("127.0.0.1", "localhost", "0.0.0.0", "::1"): + return first_ip + + # 回退到 X-Real-IP(Nginx proxy_set_header X-Real-IP $remote_addr) + real_ip = request.headers.get("X-Real-IP", "").strip() + if real_ip and real_ip not in ("127.0.0.1", "localhost", "0.0.0.0", "::1"): + return real_ip + + # 最后使用 remote_addr return request.remote_addr - - -def get_ip_location(ip: str) -> str: - """ - 根据IP获取地理位置(使用第三方API) - - Args: - ip: IP地址 - - Returns: - 地理位置信息,格式:"国家 省份 城市" - """ - if ip in ['127.0.0.1', 'localhost'] or ip.startswith('192.168.') or ip.startswith('10.'): - return "内网IP" - - try: - url = f"http://ip-api.com/json/{ip}?lang=zh-CN" - with urllib.request.urlopen(url, timeout=3) as response: - data = json.loads(response.read().decode('utf-8')) - if data.get('status') == 'success': - return f"{data.get('country', '')} {data.get('regionName', '')} {data.get('city', '')}" - except Exception as e: - logger.warning(f"获取IP地理位置失败: {e}") - - return "未知" diff --git a/src/core/redis_client.py b/src/core/redis_client.py index 9465212..b8f797c 100644 --- a/src/core/redis_client.py +++ b/src/core/redis_client.py @@ -68,7 +68,7 @@ from flask_redis import FlaskRedis # FlaskRedis 扩展实例 # ============================================================ # 在应用工厂中通过 init_redis(app) 完成绑定 -redis_client = FlaskRedis(decode_responses=True, protocol=2) +redis_client = FlaskRedis(decode_responses=True) def init_redis(app: Flask):