Skip to content

fix(plugin): dependency dynamic refresh #4334

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion app/helper/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import json
import shutil
import traceback
import site
import importlib
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Set

Expand Down Expand Up @@ -452,7 +454,7 @@ def __remove_old_plugin(pid: str):
@staticmethod
def __pip_install_with_fallback(requirements_file: Path) -> Tuple[bool, str]:
"""
使用自动降级策略,PIP 安装依赖,优先级依次为镜像站、代理、直连
使用自动降级策略安装依赖,并确保新安装的包可被动态导入
:param requirements_file: 依赖的 requirements.txt 文件路径
:return: (是否成功, 错误信息)
"""
Expand All @@ -466,12 +468,25 @@ def __pip_install_with_fallback(requirements_file: Path) -> Tuple[bool, str]:
strategies.append(("代理", base_cmd + ["--proxy", settings.PROXY_HOST]))
strategies.append(("直连", base_cmd))

# 记录当前已安装的包,以便后续刷新
before_installation = set(sys.modules.keys())

# 遍历策略进行安装
for strategy_name, pip_command in strategies:
logger.debug(f"[PIP] 尝试使用策略:{strategy_name} 安装依赖,命令:{' '.join(pip_command)}")
success, message = SystemUtils.execute_with_subprocess(pip_command)
if success:
logger.debug(f"[PIP] 策略:{strategy_name} 安装依赖成功,输出:{message}")
# 安装成功后刷新Python的模块系统
importlib.reload(site)
# 获取新安装的模块
current_modules = set(sys.modules.keys())
new_modules = current_modules - before_installation
# 重新加载新安装的模块
for module in new_modules:
if module in sys.modules:
del sys.modules[module]
logger.debug(f"[PIP] 已刷新导入系统,新加载的模块: {new_modules}")
return True, message
else:
logger.error(f"[PIP] 策略:{strategy_name} 安装依赖失败,错误信息:{message}")
Expand Down
2 changes: 1 addition & 1 deletion app/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def __setup_logger(log_file: str):
file_formatter = CustomFormatter(log_settings.LOG_FILE_FORMAT)
file_handler.setFormatter(file_formatter)
_logger.addHandler(file_handler)

# 禁止向父级log传递
_logger.propagate = False

Expand Down