- git 初始化 + .gitignore 补全(根 .env / logs / instance / __pycache__ 等) - 修复 utils/.gitignore 误将整个 utils/ 源码层忽略的问题,补入全部工具源码(含 ip2region.xdb) - 含后端全部代码:application / extensions / utils / config / migrations - 含前端 ui/(后续整体迁走) - 不含根 .env(含密钥,本地保留) Co-Authored-By: Claude <noreply@anthropic.com>
56 lines
1.5 KiB
Python
56 lines
1.5 KiB
Python
"""
|
|
IP地址工具模块
|
|
=============================================================
|
|
|
|
提供客户端IP获取和地理位置查询:
|
|
- get_client_ip: 获取客户端真实IP(需配合Flask ProxyFix使用)
|
|
- get_ip_location: 调用第三方API查询IP地理位置
|
|
"""
|
|
|
|
import json
|
|
import logging
|
|
import urllib.request
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def get_client_ip():
|
|
"""
|
|
获取客户端真实IP地址
|
|
|
|
通过Flask ProxyFix中间件由PROXY_NUM配置自动设置
|
|
request.remote_addr为真实客户端IP。未配置ProxyFix时,
|
|
request.remote_addr即为直连IP,避免客户端伪造。
|
|
|
|
Returns:
|
|
str: 客户端IP地址
|
|
"""
|
|
from flask import request
|
|
|
|
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 "未知"
|