1. 程式人生 > >flask-信號(blinker)

flask-信號(blinker)

functions blog from del 添加 var don mutable nbsp

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在其中添加數據時,自動觸發

技術分享圖片
                2. request_started = _signals.signal(request-started)                # 請求到來前執行
                5. request_finished = _signals.signal(request-finished)              # 請求結束後執行
                 
                3. before_render_template = _signals.signal(before-render-template)  # 模板渲染前執行
                4. template_rendered = _signals.signal(template-rendered)            # 模板渲染後執行
                 
                發生在2/3/4/5或不執行 got_request_exception = _signals.signal(got-request-exception)    # 請求執行出現異常時執行
                 
                6. request_tearing_down = _signals.signal(request-tearing-down)      # 請求執行完畢後自動執行(無論成功與否)
                7. appcontext_tearing_down = _signals.signal(appcontext-tearing-down)# 請求上下文執行完畢後自動執行(無論成功與否)
                 
                 
                1. appcontext_pushed = _signals.signal(appcontext-pushed)            # 請求app上下文push時執行
                
                8. appcontext_popped = _signals.signal(appcontext-popped)            # 請求上下文pop時執行
                
                message_flashed = _signals.signal(message-flashed)                   # 調用flask在其中添加數據時,自動觸發
執行順序

源碼示例

技術分享圖片
class Flask(_PackageBoundObject):

    def full_dispatch_request(self):
       
        self.try_trigger_before_first_request_functions()
        try:
            # ############### 觸發request_started 信號 ###############
            request_started.send(self)       
            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

    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.make_response(self.handle_exception(e))
            return response(environ, start_response)
        finally:
            if self.should_ignore_error(error):
                error = None
            ctx.auto_pop(error)
request_started 技術分享圖片
同上
request_finished 技術分享圖片
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
before_render_template 技術分享圖片
同上
template_rendered 技術分享圖片
class Flask(_PackageBoundObject):

    def handle_exception(self, e):
       
        exc_type, exc_value, tb = sys.exc_info()

        # ############### got_request_exception 信號 ###############
        got_request_exception.send(self, exception=e)
        handler = self._find_error_handler(InternalServerError())

        if self.propagate_exceptions:
            # if we want to repropagate the exception, we can attempt to
            # raise it with the whole traceback in case we can do that
            # (the function was actually called from the except part)
            # otherwise, we just raise the error again
            if exc_value is e:
                reraise(exc_type, exc_value, tb)
            else:
                raise e

        self.log_exception((exc_type, exc_value, tb))
        if handler is None:
            return InternalServerError()
        return handler(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.make_response(self.handle_exception(e))
            return response(environ, start_response)
        finally:
            if self.should_ignore_error(error):
                error = None
            ctx.auto_pop(error)
got_request_exception 技術分享圖片
class AppContext(object):
    def push(self):
        """Binds the app context to the current context."""
        self._refcnt += 1
        if hasattr(sys, exc_clear):
            sys.exc_clear()
        _app_ctx_stack.push(self)
        # ############## 觸發 appcontext_pushed 信號 ##############
        appcontext_pushed.send(self.app)

    def pop(self, exc=_sentinel):
        """Pops the app context."""
        try:
            self._refcnt -= 1
            if self._refcnt <= 0:
                if exc is _sentinel:
                    exc = sys.exc_info()[1]
                # ############## 觸發 appcontext_tearing_down 信號 ##############
                self.app.do_teardown_appcontext(exc)
        finally:
            rv = _app_ctx_stack.pop()
        assert rv is self, Popped wrong app context.  (%r instead of %r)             % (rv, self)

        # ############## 觸發 appcontext_popped 信號 ##############
        appcontext_popped.send(self.app)

class RequestContext(object):
    def push(self):
        top = _request_ctx_stack.top
        if top is not None and top.preserved:
            top.pop(top._preserved_exc)

        app_ctx = _app_ctx_stack.top
        if app_ctx is None or app_ctx.app != self.app:
            
            # ####################################################
            app_ctx = self.app.app_context()
            app_ctx.push()
            self._implicit_app_ctx_stack.append(app_ctx)
        else:
            self._implicit_app_ctx_stack.append(None)

        if hasattr(sys, exc_clear):
            sys.exc_clear()

        _request_ctx_stack.push(self)

        # Open the session at the moment that the request context is
        # available. This allows a custom open_session method to use the
        # request context (e.g. code that access database information
        # stored on `g` instead of the appcontext).
        self.session = self.app.open_session(self.request)
        if self.session is None:
            self.session = self.app.make_null_session()

class Flask(_PackageBoundObject):


    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.make_response(self.handle_exception(e))
            return response(environ, start_response)
        finally:
            if self.should_ignore_error(error):
                error = None
            ctx.auto_pop(error)


    def pop(self, exc=_sentinel):
        app_ctx = self._implicit_app_ctx_stack.pop()

        try:
            clear_request = False
            if not self._implicit_app_ctx_stack:
                self.preserved = False
                self._preserved_exc = None
                if exc is _sentinel:
                    exc = sys.exc_info()[1]

                # ################## 觸發 request_tearing_down 信號 ##################
                self.app.do_teardown_request(exc)

                # If this interpreter supports clearing the exception information
                # we do that now.  This will only go into effect on Python 2.x,
                # on 3.x it disappears automatically at the end of the exception
                # stack.
                if hasattr(sys, exc_clear):
                    sys.exc_clear()

                request_close = getattr(self.request, close, None)
                if request_close is not None:
                    request_close()
                clear_request = True
        finally:
            rv = _request_ctx_stack.pop()

            # get rid of circular dependencies at the end of the request
            # so that we don‘t require the GC to be active.
            if clear_request:
                rv.request.environ[werkzeug.request] = None

            # Get rid of the app as well if necessary.
            if app_ctx is not None:
                # ####################################################
                app_ctx.pop(exc)

            assert rv is self, Popped wrong request context.                   (%r instead of %r) % (rv, self)

    def auto_pop(self, exc):
        if self.request.environ.get(flask._preserve_context) or            (exc is not None and self.app.preserve_context_on_exception):
            self.preserved = True
            self._preserved_exc = exc
        else:
            self.pop(exc)
request_tearing_down 技術分享圖片
同上
appcontext_tearing_down 技術分享圖片
同上
appcontext_tearing_down 技術分享圖片
同上
appcontext_pushed 技術分享圖片
同上
appcontext_popped 技術分享圖片
def flash(message, category=message):
    """Flashes a message to the next request.  In order to remove the
    flashed message from the session and to display it to the user,
    the template has to call :func:`get_flashed_messages`.

    .. versionchanged:: 0.3
       `category` parameter added.

    :param message: the message to be flashed.
    :param category: the category for the message.  The following values
                     are recommended: ``‘message‘`` for any kind of message,
                     ``‘error‘`` for errors, ``‘info‘`` for information
                     messages and ``‘warning‘`` for warnings.  However any
                     kind of string can be used as category.
    """
    # Original implementation:
    #
    #     session.setdefault(‘_flashes‘, []).append((category, message))
    #
    # This assumed that changes made to mutable structures in the session are
    # are always in sync with the session object, which is not true for session
    # implementations that use external storage for keeping their keys/values.
    flashes = session.get(_flashes, [])
    flashes.append((category, message))
    session[_flashes] = flashes

    # ############### 觸發 message_flashed 信號 ###############
    message_flashed.send(current_app._get_current_object(),
                         message=message, category=category)
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 flask import Flask, current_app, flash, render_template from flask.signals import _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()

3.其他

1.Flask中的特殊裝飾器和信號有什麽區別?

-信號不需要返回值
-裝飾器的返回值有意義

2.信用用於做什麽?

-自定義一些沒有返回值的操作
-降低代碼之間的耦合

flask-信號(blinker)