Flask的信号
from flask import Flask,signals,render_template
app = Flask(__name__)
# 往信号中注册函数
#1给信号绑定要执行的函数
#无需管调用,因为flask,已经给我们设置调用点
def func(*args,**kwargs):
print('触发型号',args,kwargs)
#与该信号进行绑定
signals.request_started.connect(func)
# signals.request_started.send
# 触发信号: signals.request_started.send()
@app.before_first_request
def before_first1(*args,**kwargs):
print("befor_first_request")
@app.before_request
def before_first3(*args,**kwargs):
print("befor_request")
@app.route('/',methods=['GET',"POST"])
def index():
print('视图')
return "视图"
if __name__ == '__main__':
# app.wsgi_app
app.run()
# 输出结果>>>:
# befor_first_request
# 触发型号 (<Flask '信号'>,) {}
# befor_request
# 视图
自定义信号
from flask import Flask, current_app, flash, render_template
from flask.signals import _signals
app = Flask(import_name=__name__)
# 自定义信号
xxxxx = _signals.signal('xxxxx')
def func(sender,a):
print(sender,a)
print("我是自定义信号")
# 自定义信号中注册函数
xxxxx.connect(func)
@app.route("/x")
def index():
# 触发信号
xxxxx.send("sb",a="1")
return 'Index'
if __name__ == '__main__':
app.run()