flask信号

flask-信号

 

Flask框架中的信号基于blinker,其主要就是让开发者可是在flask请求过程中定制一些用户行为。

1
pip3 install blinker

1. 内置信号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
request_started= _signals.signal('request-started')               # 请求到来前执行
request_finished= _signals.signal('request-finished')             # 请求结束后执行
 
before_render_template= _signals.signal('before-render-template'# 模板渲染前执行
template_rendered= _signals.signal('template-rendered')           # 模板渲染后执行
 
got_request_exception= _signals.signal('got-request-exception')   # 请求执行出现异常时执行
 
request_tearing_down= _signals.signal('request-tearing-down')     # 请求执行完毕后自动执行(无论成功与否)
appcontext_tearing_down= _signals.signal('appcontext-tearing-down')# 应用上下文执行完毕后自动执行(无论成功与否)
 
appcontext_pushed= _signals.signal('appcontext-pushed')           # 应用上下文push时执行
appcontext_popped= _signals.signal('appcontext-popped')           # 应用上下文pop时执行
message_flashed= _signals.signal('message-flashed')               # 调用flask在其中添加数据时,自动触发

源码示例

 request_started
 request_finished
 before_render_template
 template_rendered
 got_request_exception
 request_tearing_down
 appcontext_tearing_down
 appcontext_tearing_down
 appcontext_pushed
 appcontext_popped
 message_flashed

2. 自定义信号

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flaskimport Flask, current_app, flash, render_template
from flask.signalsimport _signals
 
app= Flask(import_name=__name__)
 
 
# 自定义信号
xxxxx= _signals.signal('xxxxx')
 
 
def func(sender,*args,**kwargs):
    print(sender)
 
# 自定义信号中注册函数
xxxxx.connect(func)
 
 
@app.route("/x")
def index():
    # 触发信号
    xxxxx.send('123123', k1='v1')
    return 'Index'
 
 
if __name__== '__main__':
    app.run()

posted on 2021-07-28 17:23  向往1  阅读(12)  评论(0编辑  收藏  举报

导航

……