Flask框架中的信号基于blinker,其主要就是让开发者可是在flask请求过程中定制一些用户行为。
pip3 install blinker
内置信号
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
class Flask(_PackageBoundObject):
...
def full_dispatch_request(self):
# ######### 执行before_first_request #########
self.try_trigger_before_first_request_functions()
try:
# ############### 触发request_started 信号 ###############
request_started.send(self)
# 调用before_request
rv = self.preprocess_request()
if rv is None:
# 执行试图函数 视图函数里执行模板渲染信号
rv = self.dispatch_request()
except Exception as e:
rv = self.handle_user_exception(e)
response = self.make_response(rv)
response = self.process_response(response)
# ############### request_finished 信号 ###############
request_finished.send(self, response=response)
return response
- before_render_template 与 template_rendered
def render_template(template_name_or_list, **context):
ctx = _app_ctx_stack.top
ctx.app.update_template_context(context)
return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
context, ctx.app)
def _render(template, context, app):
# ############### before_render_template 信号 ###############
before_render_template.send(app, template=template, context=context)
rv = template.render(context) # 渲染模板
# ############### template_rendered 信号 ###############
template_rendered.send(app, template=template, context=context)
return rv
- got_request_exception
class Flask():
def handle_exception(self, e):
exc_type, exc_value, tb = sys.exc_info()
############### got_request_exception 信号 ###############
got_request_exception.send(self, exception=e)
def wsgi_app(self, environ, start_response):
ctx = self.request_context(environ)
ctx.push()
error = None
try:
try:
response = self.full_dispatch_request()
except Exception as e:
error = e
# 这里这里这里这里这里这里这里这里这里这里这里这里 #
response = self.handle_exception(e)
return response(environ, start_response)
finally:
if self.should_ignore_error(error):
error = None
ctx.auto_pop(error)
其他信号源码 : https://www.cnblogs.com/wupeiqi/p/8249576.html
信号执行顺序:
请求扩展与信号区别:
- 请求扩展有返回值会终止请求 https://blog.csdn.net/Waller_/article/details/105391302
- 信号只能执行不能终止请求