Flask 信号机制
flask信号
信号使用详解:
信号使用分为三步
定义信号
- ```python
from flask import Flask
from signal import visit_signalapp = Flask(name)@app.route(‘/‘)
def func1():username = request.args.get('username') if username: g.user = username visit_signal.send() else: return 'hello world'
1
2
3
4
5
6
7
8
9
- ```python
from blinker import Namespace
my_pace = Namepace()
visit_signal = my_pace.signal('visit-signal')
def func(sender):
from flask import g
print(g.user)
visit_signal.connect(func)
- ```python
监听信号
- ```python
visit_signal.send()
#设置监听1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
------
### flask自带的信号机制:
#### 模板渲染时传出的信号:
- ```python
#正常信号监听
from flask import Flask,render_template,template_rendered
app = Flask(__name__)
***********************************************************
#其一
def template_rendered_func(sender,template,context):
print('sender:',sender)
print('template:',template)
print('context',context)
template_randered.context(template_rendered_func)
***********************************************************
@app.route('/')
def func1():
return render_template('index.html')
- ```python
#异常信号监听 from flask import Flask,render_template,template_rendered,got_request_exception app = Flask(__name__) *********************************************************** #其二 def request_exception_log(sender,*args,**kwargs): print(sender) print(args) print(kwargs) got_request_exception.connect(request_exception_log) *********************************************************** @app.route('/') def func1(): return render_template('index.html')