1、Flask中信号简介

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

2、内置信号

  Flask中内置信号在·signals.py中定义:

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

   源码示例:

def render_template(template_name_or_list, **context):
    """Renders a template from the template folder with the given
    context.

    :param template_name_or_list: the name of the template to be
                                  rendered, or an iterable with template names
                                  the first one existing will be rendered
    :param context: the variables that should be available in the
                    context of the template.
    """
    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):
    """Renders the template and fires the signal"""
    
    # ############### 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
template_rendered

相关文章:

  • 2022-12-23
  • 2021-07-19
  • 2021-12-02
  • 2022-02-20
  • 2021-11-03
猜你喜欢
  • 2022-12-23
  • 2021-12-03
  • 2022-12-23
  • 2022-12-23
  • 2022-01-22
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案