forked from iti-framework/iTi-Flask
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.8 KiB
Python
60 lines
1.8 KiB
Python
import importlib
|
|
from flask import Blueprint
|
|
import os
|
|
import json
|
|
|
|
plugin_bp = Blueprint("plugin", __name__, url_prefix="/plugin")
|
|
|
|
PLUGIN_ENABLE_FOLDERS = []
|
|
PLUGIN_IMPORTLIB = []
|
|
|
|
|
|
def init_plugin(app) -> None:
|
|
"""
|
|
初始化插件
|
|
"""
|
|
global PLUGIN_ENABLE_FOLDERS
|
|
app.register_blueprint(plugin_bp)
|
|
|
|
# 载入插件 PLUGIN_ENABLE_FOLDERS 是插件文件夹名
|
|
PLUGIN_ENABLE_FOLDERS = app.config.get("PLUGIN_ENABLE_FOLDERS", [])
|
|
|
|
for folder in PLUGIN_ENABLE_FOLDERS:
|
|
plugin_info = {
|
|
"plugin_name": folder,
|
|
}
|
|
|
|
try:
|
|
if os.path.exists("plugins/" + folder + "/__init__.json"):
|
|
with open(
|
|
"plugins/" + folder + "/__init__.json", "r", encoding="utf-8"
|
|
) as f:
|
|
plugin_info = json.loads(f.read())
|
|
# 将插件全部载入
|
|
PLUGIN_IMPORTLIB.append(importlib.import_module("plugins." + folder))
|
|
print(f" * Plugin: Loaded plugin: {plugin_info['plugin_name']} ...")
|
|
except BaseException as e:
|
|
info = (
|
|
f" * Plugin: Crash a error when loading {plugin_info['plugin_name'] if len(plugin_info) != 0 else 'plugin'} :"
|
|
+ "\n"
|
|
)
|
|
app.logger.error(info)
|
|
app.logger.exception(e)
|
|
|
|
|
|
def broadcast_execute(app, function_name):
|
|
for plugin in PLUGIN_IMPORTLIB:
|
|
try:
|
|
# 初始化完成事件
|
|
try:
|
|
getattr(plugin, function_name)(app)
|
|
except AttributeError: # 没有插件启用事件就不调用
|
|
pass
|
|
|
|
except BaseException as e:
|
|
app.logger.exception(e)
|
|
|
|
if function_name == "event_finish":
|
|
with app.app_context():
|
|
broadcast_execute(app, "event_context")
|