Flask Signals

Flask 官方推荐 Blinker

1. 创建 Signals,推荐使用 Namespace

from blinker import Namespace

my_signals = Namespace()
sig = my_signals.signal('zh')

2. 订阅

app = Flask(__name__)

def pt(sender, **value):
    print(sender)
    print(value)

sig.connect(pt, app)

3. 发射信号

@app.route('/ts')
def test_signals():
    sig.send(app, abc=123)
    return 'ok'

4. 注解形式订阅

@sig.connect
def pt(sender, **value):
    print(sender)
    print(value)

5. 验证发送者形式订阅

@sig.connect_via(app)
def pt(sender, **value):
    print(sender)
    print(value)

展开阅读全文