Flask --- signal,

Source: Internet
Author: User

Flask --- signal,

I. flask-Signal

The signal in the Flask framework is based on blinker

Flask-SIGNAL INSTALLATION

Pip3 install blinker

10 Built-in Signals

1. 10 Built-in signals: 2. request_started = _ signals. signal ('request-started') # execute 5 before the request arrives. request_finished = _ signals. signal ('request-finished') # execute after the request ends 3. before_render_template = _ signals. signal ('before-render-template') # execute the template before rendering. template_rendered = _ signals. signal ('template-rendered') # After the template is rendered, execute 2/3/4/5 or do not execute got_request_exception = _ signals. signal ('got-request-exception') # When an exception occurs during request execution 6. request_tearing_down = _ signals. signal ('request-tearing-lower') # Automatic execution after the request is executed (whether successful or not) 7. appcontext_tearing_down = _ signals. signal ('appcontext-tearing-low') # Automatic execution after the request context is executed (whether successful or not) 1. appcontext_pushed = _ signals. signal ('appcontext-pushed') #8. appcontext_popped = _ signals. signal ('appcontext-poped') # execute message_flashed = _ signals when requesting context pop. signal ('message-flashed') # It is automatically triggered when you call flask to add data to it.

Ii. Signal Source Code the entire process source code

Def wsgi_app (self, environ, start_response): ctx = self. request_context (environ) # instantiate the context object ctx. push () error = None try: # execute: before decorator function, view function, after decorator function response = self. full_dispatch_request () failed t Exception as e: #(6. if an exception occurs during request execution, it is the execution of got_request_exception) error = e response = self. handle_exception (e) handle T: error = sys. exc_info () [1] raise # return the processed content to the browser return response (environ, start_response) finally: if self. should_ignore_error (error): error = None # End ctx. auto_pop (error) # (ctx is the requestContext object and runs the ctx pop method)
Def wsgi_app
Def push (self): app_ctx = _ app_ctx_stack.top if app_ctx is None or app_ctx.app! = Self. app: # app_ctx = AppContext (self. app) (execute the push in app_context in app_ctx.push () after instantiation) app_ctx = self. app. app_context () # Place the app to the queue and put it in the Local # method for triggering appcontext_push (1. the first signal has been triggered and executed.) app_ctx.push () self. _ implicit_app_ctx_stack.append (app_ctx) # (app_ctx is the object created by AppContext) else: self. _ implicit_app_ctx_stack.append (None) if hasattr (sys, 'exc _ clear'): sys. exc_clear () # Add the RequestContext object to Local _ 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 ()
Def push (
Def full_dispatch_request (self): # execute: @ before_first_request all functions decorated by self. try_trigger_before_first_request_functions () try: request_started.send (self) #(2. the view function is not executed. The request just comes in and executes request_started.send (self) rv = self. preprocess_request () if rv is None: # execute the view function # execute session rv = self. dispatch_request () # (execute the view function) # If a template exists, execute #3. before_render_template = _ signals. signal ('before-render-template') # execute the template before rendering #4. template_rendered = _ signals. signal ('template-rendered') # execute the template after rendering # execute the two templates and then execute the following transform t Exception as e: rv = self. handle_user_exception (e) # Run: @ after_request decorate all the functions and save session return self. finalize_request (rv)
Def full_dispatch_request
Def process_response (self, response): ctx = _ request_ctx_stack.top bp = ctx. request. blueprint funcs = ctx. _ after_request_functions if bp is not None and bp in self. after_request_funcs: funcs = chain (funcs, reversed (self. after_request_funcs [bp]) if None in self. after_request_funcs: funcs = chain (funcs, reversed (self. after_request_funcs [None]) # execute all the functions decorated by @ after_request for handler in funcs: response = handler (response) # process session if not self. session_interface.is_null_session (ctx. session): self. save_session (ctx. session, response) return response
Def process_response
Def finalize_request (self, rv, from_error_handler = False): response = self. make_response (rv) try: response = self. process_response (response) request_finished.send (self, response = response) #(5. after the view function is executed, run request_finished.send) fail t Exception: if not from_error_handler: raise self. logger. exception ('request finalizing failed with an ''error while handling an error') return response
Def finalize_request
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)
Def auto_pop
Def pop (self, exc = _ sentinel): app_ctx = self. _ implicit_app_ctx_stack.pop () (# app_ctx is AppContext (self. app) object) 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] 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 pop
Def do_teardown_request (self, exc = _ sentinel): if exc is _ sentinel: exc = sys. exc_info () [1] funcs = reversed (self. teardown_request_funcs.get (None, () bp = _ request_ctx_stack.top.request.blueprint if bp is not None and bp in self. teardown_request_funcs: funcs = chain (funcs, reversed (self. teardown_request_funcs [bp]) for func in funcs: func (exc) request_tearing_down.send (self, exc = exc) #(6. request_tearing_down is automatically executed after the request is executed (whether successful or not ))
Def do_teardown_request
Def do_teardown_appcontext (self, exc = _ sentinel): if exc is _ sentinel: exc = sys. exc_info () [1] for func in reversed (self. teardown_appcontext_funcs): func (exc) appcontext_tearing_down.send (self, exc = exc) (#7. the appcontext_tearing_down request is automatically executed after the context is executed (whether successful or not ))
Def do_teardown_appcontext
Def pop (self, exc = _ sentinel): try: self. _ refcnt-= 1 if self. _ refcnt <= 0: if exc is _ sentinel: exc = sys. exc_info () [1] 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.send (self. app) (#8. appcontext_popped # executed when the context pop is requested)
Def pop

3. Custom Signal

 

From flask import Flask, flash
From flask. signals import _ signals
App = Flask (_ name __)

Wh = _ signals. signal ('wh ')


# Define functions
Def luominwen (* args, ** kwargs ):
Print ('girl loan', args, kwargs)

# Define functions
Def shaowei (* args, ** kwargs ):
Print ('little girl ', args, kwargs)

# Register the function to the request_started signal: add it to this list
Wh. connect (luominwen)
Wh. connect (shaowei)

 

@ App. route ('/Index ')
Def index ():
# Trigger this signal: Execute all functions registered to the list
# Sending text messages and emails,
Wh. send (sender = 'xxx', a1 = 123, a2 = 456)
Return "xx"

If _ name _ = '_ main __':
App. _ call __
App. run ()

 

Problem:
What is the difference between special decorators and signals?
-The return value of the decorator is meaningful.
-What is the signal used?
-Reduced Code Coupling

Iv. built-in django Signals

 

Request/response signals request_started # automatically triggers request_finished before the Request arrives # after the Request ends, the got_request_exception is automatically triggered # after the Request is abnormal, before the Model signals pre_init # django modal is automatically triggered to execute its constructor method, the post_init # django modal is automatically triggered to execute its constructor method. Before the pre_save # django modal object is saved, after the post_save # django modal object is automatically triggered and saved, the pre_delete # django modal object is automatically triggered. After the post_delete # django modal object is deleted, automatically trigger m2m_changed # before and after the third table (add, remove, clear) using the m2m field in django modal, automatically trigger class_prepared # When the program is started, detects modal classes in registered apps. For each class, the Management signals pre_migrate is automatically triggered. # After the migrate command is executed, the post_migrate is automatically triggered. # After the migrate command is executed, test signals setting_changed # template_rendered is automatically triggered when you use test to modify the configuration file # When you use test to Test the rendering template, Database Wrappers connection_created is automatically triggered # When you create a Database connection

 

Requirement: For the Sina interview, there are 12 tables in the database. Each table records a log when creating a data record.
Rewrite the save method or use a signal to find a function to register the signal.
Note that registering a function is: place the registered function in the position where the file is just started, for example, __init. py.
Registration letterNumber:

def func(*args,**):    print(args,kwargs)post_save.connect(func)

V1 = [,] v2 = [,] from itertools import chainff = [] for I in chain (v1, v2 ): # chain connects two lists in one ff. append (I) print (ff) # [11, 22, 33, 44, 1, 4, 7, 5]
Application of chain

The flask signal is not generated by itself and is replaced by others, and all these signals can be replaced by the decorator. However, Django has some special
That is, the model operations have no decorator at all, and are completed with built-in signals.

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.