【Flask】Flask common signals


Using a signal is divided into 3 steps, the first is to define a signal, the second is to monitor a signal, and the third is to send a signal.

1. Define a signal: To define a signal, you need to use the namespace class of the blinker package to create a namespace. For example, define a signal when a view function is accessed. The sample code is as follows:

1  # The role of Namespace: In order to prevent the problem of signal name conflict when multiple people develop 
2  from blinker import Namespace
 3  
4 mysignal = Namespace()
 5 visit_signal = mysignal.signal( ' visit-signal ' )

 

2. Monitor the signal: Use the connect method of the singal object to monitor the signal. In this method, you need to pass a function to receive what to do after listening to the signal. The sample code is as follows:

1 def visit_func(sender,username):
2 print(sender)
3 print(username)
4 mysignal.connect(visit_func)

 

3. Sending a signal: Sending a signal uses the send method of the singal object, which can pass some other parameters in the past. The sample code is as follows:

1 mysignal.send(username='saber')

 

### Flask's built-in signals:
1. template_rendered: The signal after the template is rendered.
2. before_render_template: The signal before the template is rendered.
3. request_started: The template starts rendering.
4. request_finished: Template rendering is complete.
5. request_tearing_down: The signal that the request object is destroyed.
6. got_request_exception: a signal that the view function has an exception. Generally, this signal can be monitored to record abnormal information of the website.
7. appcontext_tearing_down: The signal that the app context is destroyed.
8. appcontext_pushed: The signal that the app context is pushed onto the stack.
9. appcontext_popped: The signal that the app context was pushed out of the stack
10. message_flashed: The signal that Flask's `flashed` method was called.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325217554&siteId=291194637