Flask之信号

信号的作用

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

内置信号

内置信号是flask请求过程中源码中定义的。
不需要我们定义和触发,只要写了函数跟它对应,函数执行到这,就会触发函数执行。

所有类型的信号

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在其中添加数据时,自动触发

内置信号的使用案例(在模板渲染前-记录日志)

from flask import Flask, render_template

app = Flask(__name__)
app.debug = True

# 我们现在想在模板渲染之 : 记录日志  使用内置信号实现
# 1 写一个函数
def before_render(*args, **kwargs):
    print(args)
    print(kwargs)
    # 谁(ip) 在什么时间  访问了哪个页面(template)
    print('记录日志,模板要渲染了')

# 2 跟内置信号绑定
from flask.signals import before_render_template
before_render_template.connect(before_render)

# 3 源码中触发信号执行(我们不需要动)
# before_render_template.send()  源码再模板渲染之前,它写死了

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/login')
def login():

    return render_template('login.html')
if __name__ == '__main__':
    app.run()

自定义信号

from flask import Flask, render_template
# 导入模块
from flask.signals import _signals
import pymysql

app = Flask(__name__)
app.debug = True

# 1 定义信号
# 自定义信号
db_save = _signals.signal('db_save')

# 2 写一个函数
def db_save_fun(*args, **kwargs):
    print(args)
    print(kwargs)
    print('表数据插入了')

db_save.connect(db_save_fun)

# 3 触发信号执行(需要我们做)
# before_render_template.send()  源码再模板渲染之前,它写死了

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/create_article')
def create_article():
    conn = pymysql.connect(host='127.0.0.1', user='root', password='root', database='cnblogs')
    cursor = conn.cursor()
    cursor.execute('insert into article (title,author) VALUES (%s,%s)', args=['测试测试标题', '测试作者测试'])
    conn.commit()
    # 手动触发信号
    db_save.send(table_name='article',info={'title':'测试测试标题','author':'测试作者测试'})
    return '插入成功'


if __name__ == '__main__':
    app.run()

'''
# 步骤:
# 1 定义信号
db_save = _signals.signal('db_save')

# 2 写一个函数
def db_save_fun(*args, **kwargs):
    print(args)
    print(kwargs)
    print('表数据插入了')

# 3 跟自定义置信号绑定
db_save.connect(db_save_fun)


# 3 触发信号执行(需要我们做)
db_save.send()  # 需要在代码中写,可以传参数,传入的参数--》db_save_fun 能拿到
'''
posted @ 2024-03-07 16:02  wellplayed  阅读(7)  评论(0编辑  收藏  举报