91 lines
2.8 KiB
Python
91 lines
2.8 KiB
Python
|
|
#!/usr/bin/env python3
|
|||
|
|
"""修复 Redis 连接问题的脚本 - 直接编辑文件"""
|
|||
|
|
|
|||
|
|
import sys
|
|||
|
|
|
|||
|
|
# 读取原始文件
|
|||
|
|
config_path = "/app/app/config.py"
|
|||
|
|
with open(config_path, "r", encoding="utf-8") as f:
|
|||
|
|
lines = f.readlines()
|
|||
|
|
|
|||
|
|
# 找到 create_redis_client 方法的开始
|
|||
|
|
start_idx = None
|
|||
|
|
for i, line in enumerate(lines):
|
|||
|
|
if "def create_redis_client(self)" in line:
|
|||
|
|
start_idx = i
|
|||
|
|
break
|
|||
|
|
|
|||
|
|
if start_idx is None:
|
|||
|
|
print("ERROR: Could not find create_redis_client method")
|
|||
|
|
sys.exit(1)
|
|||
|
|
|
|||
|
|
# 找到方法结束(下一个 def 或 class)
|
|||
|
|
end_idx = None
|
|||
|
|
for i in range(start_idx + 1, len(lines)):
|
|||
|
|
if lines[i].strip().startswith("def ") or lines[i].strip().startswith("class "):
|
|||
|
|
end_idx = i
|
|||
|
|
break
|
|||
|
|
|
|||
|
|
if end_idx is None:
|
|||
|
|
end_idx = len(lines)
|
|||
|
|
|
|||
|
|
print(f"Found method at lines {start_idx+1} to {end_idx}")
|
|||
|
|
|
|||
|
|
# 新的方法实现
|
|||
|
|
new_method = ''' def create_redis_client(self) -> aioredis.Redis:
|
|||
|
|
"""创建 Redis 异步客户端实例。
|
|||
|
|
|
|||
|
|
使用单独的 host/port/password 参数,避免 URL 解析问题
|
|||
|
|
(特别是密码中包含特殊字符 ! @ # 时)。
|
|||
|
|
|
|||
|
|
自动附加 protocol=2 参数,强制使用 RESP2 协议。
|
|||
|
|
原因:Windows 版 Redis 3.x 不支持 RESP3 协议(HELLO 命令),
|
|||
|
|
而 redis-py 8.0+ 默认使用 RESP3,会导致连接失败。
|
|||
|
|
全项目统一使用此方法创建 Redis 客户端,避免协议不匹配。
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
aioredis.Redis: 配置好的 Redis 异步客户端
|
|||
|
|
"""
|
|||
|
|
# 如果 redis_url 为空,使用默认值
|
|||
|
|
if not self.redis_url:
|
|||
|
|
# 默认值:本地 Redis
|
|||
|
|
return aioredis.Redis(
|
|||
|
|
host="localhost",
|
|||
|
|
port=6379,
|
|||
|
|
protocol=2,
|
|||
|
|
decode_responses=True
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 解析 REDIS_URL 提取连接参数
|
|||
|
|
# 格式: redis://:password@host:port/db
|
|||
|
|
from urllib.parse import urlparse
|
|||
|
|
parsed = urlparse(self.redis_url)
|
|||
|
|
|
|||
|
|
# 提取密码(去掉用户名部分,如果存在的话)
|
|||
|
|
password = parsed.password
|
|||
|
|
if not password:
|
|||
|
|
# 尝试从 netloc 中提取(格式 :password@host)
|
|||
|
|
netloc = parsed.netloc
|
|||
|
|
if "@" in netloc:
|
|||
|
|
password = netloc.split("@")[0].split(":")[-1]
|
|||
|
|
|
|||
|
|
return aioredis.Redis(
|
|||
|
|
host=parsed.hostname or "localhost",
|
|||
|
|
port=parsed.port or 6379,
|
|||
|
|
password=password,
|
|||
|
|
db=parsed.path and int(parsed.path.lstrip("/")) or 0,
|
|||
|
|
protocol=2,
|
|||
|
|
decode_responses=True
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
'''
|
|||
|
|
|
|||
|
|
# 替换方法
|
|||
|
|
new_lines = lines[:start_idx] + [new_method] + lines[end_idx:]
|
|||
|
|
|
|||
|
|
# 写回文件
|
|||
|
|
with open(config_path, "w", encoding="utf-8") as f:
|
|||
|
|
f.writelines(new_lines)
|
|||
|
|
|
|||
|
|
print("Fixed!")
|