这两天想把基于 Flask 的 Telegram Bot 重新写一下,之前一把梭的太难看了。 顺便把一直想写的插件系统实现一下,这里单独把插件部分摘出来记录分享一下

./main.py

from flask import Flask, request, Response
import os, sys

app = Flask(__name__)
app.debug = True
sys.dont_write_bytecode = True

# 插件部分
print("Loading plugins...")
sys.path.append(os.getcwd() + '/plugins')  # 设置一下 module 的搜索路径
plugins = []
for file in os.listdir("./plugins"):
    filename = file.split('.')[0]
    plugin = __import__(filename)  # for 起来 magic 一把梭
    plugins.append(plugin)
    print "Loaded Plugin '%s' with priority %s." % (filename, plugin.priority)
plugins.sort(key=lambda x: x.priority)  # 一个一把梭的插件优先级实现
# 看一看最后 EventLoop 的处理顺序
print("Plugin order:")
for plugin in plugins:
    print(plugin.__name__)
print("Plugins ready.")
# 业务部分
@app.route("/")
def index():
    # EventLoop
    for plugin in plugins:
        plugin.plugin_main(request.data)
        if update.handled:
            print("meet handled, stopping EventLoop.")
            break
    return ""

./plugins/example.py

#!/usr/bin/env python
# coding:utf-8

priority = 100

def plugin_main(update):
    # Do something...
    update.handled = True  # 阻止优先级更低的插件接收到 request

if __name__ == "__main__":
    print("This is a plugin.")

终端输出

(.env) stonemoe@server /h/w/api.stone.moe> python dummy.py
Loading plugins...
Loaded Plugin 'plugin1' with priority 0.
Loaded Plugin 'example' with priority 100.
Loaded Plugin 'plugin2' with priority 1.
Plugin order:
plugin1
plugin2
example
Plugins ready.
 * Running on http://127.0.0.1:8081/ (Press CTRL+C to quit)