Files
37duAutomation/webhost/backend/plugins/__init__.py
T
puddy 53913f0c7d refactor(workflows): 统一替换 yingdao 目录引用为 workflows
1.  将所有文档、代码中对 `yingdao/` 目录的引用替换为 `workflows/`,统一影刀版代码的命名空间
2.  调整 workflows/share 模块内的路径引用与文档注释,确保一致性
3.  同步更新测试代码与配置文件中的旧目录引用
2026-09-08 16:16:35 +08:00

68 lines
2.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""插件注册表——目录动态扫描加载。
加载约定(扫描协议):
- 插件形态:plugins/ 下的**目录包**(含 __init__.py,在其中定义 ScenePlugin 子类并
PLUGINS.append,如 seal_check/)。顶层单模块(*.py)仅用于兼容旧 demo/platform_check。
- 私有辅助文件**必须用 `_` 前缀**(如 _utils.py、_common/),扫描时一律排除,
避免被误当作插件 import。
- 只有继承 ScenePlugin 并通过 PLUGINS.append 注册的才会进入注册表;_ 前缀约定
确保辅助模块根本不会被 import,杜绝误注册与无用告警。
- 同名冲突:目录优先于同名 .py(先收目录再收 py,同名仅保留目录)。
- 单个插件加载失败记 ERROR 并保留堆栈首行后跳过,不拖垮整体启动。
阶段二(权限):把「有权限的插件名」传给 load_plugins(allowed) 即可,无权限不 import。
届时触发点建议从「import 副作用」改为由 main.py 在应用启动时显式调用 load_plugins(),
以便每次按登录账号动态决定允许集。
"""
from __future__ import annotations
import importlib
import logging
import pathlib
import traceback
from webhost.backend.plugins.base import PLUGINS # noqa: F401 由 base 构造空注册表
_PLUGINS_ROOT = pathlib.Path(__file__).resolve().parent
_PKG_NAME = __name__
_LOGGER = logging.getLogger(__name__)
def _discover_modules() -> list:
"""发现插件模块:目录优先,排除 base 与 `_` 前缀的私有文件。"""
names: list = []
seen: set = set()
for d in sorted(_PLUGINS_ROOT.iterdir()):
if not d.is_dir() or d.name.startswith("_") or d.name == "__pycache__":
continue
if (d / "__init__.py").exists():
names.append(d.name)
seen.add(d.name)
for f in sorted(_PLUGINS_ROOT.glob("*.py")):
if f.name in ("__init__.py", "base.py") or f.name.startswith("_"):
continue
if f.stem not in seen: # 已被同名目录占用则跳过
names.append(f.stem)
return names
def load_plugins(allowed: set = None) -> None:
"""动态加载插件。allowed 为空 = 全量;否则仅加载白名单内的插件。
单插件加载失败记 ERROR(含堆栈首行)后跳过,不拖垮整体启动。
"""
allowed = allowed if allowed is not None else set()
for _mod in _discover_modules():
if allowed and _mod not in allowed:
_LOGGER.info("插件 %s 不在权限白名单,跳过加载", _mod)
continue
try:
importlib.import_module(f"{_PKG_NAME}.{_mod}")
except Exception as _exc: # noqa: BLE001
_LOGGER.error("插件 %s 加载失败,已跳过\n%s", _mod,
traceback.format_exc(limit=1))
# 触发加载(阶段一:全量;阶段二改由 main.py 显式调用并传入权限白名单)
load_plugins()