Describes the signals signal mechanism in the Python Flask framework, and flasksignals
Flask provides the Signals function and is a message distribution mechanism. Similar to Hooks ). Using the signal function can reduce program coupling and break down complex business models. For example, after updating the product data, you can send a signal. When the product data needs to be processed, the signal can be captured for processing. For example, you need to create a product cache or update search indexes.
Define Signal
The Flask signal function uses the Blinker module. Therefore, you must first install the Blinker module.
pip install blinker
Define a signal:
from blinker import Namespaceproduct_saved = Namespace()
You can also use the singles object wrapped in Flask:
from flask.singles import Namespace
Send signal
The method for sending signals must contain an app instance. The example is as follows:
product_saved.send(app, product=product)
You can add parameters to be passed after the app, but they must be in name = value format. You cannot use a single variable name.
Receiving Signal
You can use the connect_via modifier function to receive signals:
@product_saved.connect_via(app)def updateCache(app, product): print(product)
Flask has the following core signals:
1. flask. template_rendered
This signal is sent after a template is rendered successfully. The template for signal transmission is an instance of the template, and the context is an environment object and a dictionary.
Subscription example:
def log_template_renders(sender, template, context, **extra): sender.logger.debug('Rendering template "%s" with context %s', template.name or 'string template', context)from flask import template_renderedtemplate_rendered.connect(log_template_renders, app)
2. flask. request_started
This signal is sent before the request starts and after the request environment is set. Because the request environment has been bound, the subscriber can use a standard Global Proxy such as request to operate the request.
Subscription example:
def log_request(sender, **extra): sender.logger.debug('Request context is set up')from flask import request_startedrequest_started.connect(log_request, app)flask.request_finished
This signal is sent before sending a response to the client. The response of the signal is the response to be sent.
Subscription example:
def log_response(sender, response, **extra): sender.logger.debug('Request context is about to close down. ' 'Response: %s', response)from flask import request_finishedrequest_finished.connect(log_response, app)flask.got_request_exception
This signal is sent when an exception occurs in the request. It sends messages between before standard exception handling. In the debugging mode, although no exception is handled, this signal is also sent when an exception occurs. The exception of signal transmission is an exception object.
Subscription example:
def log_exception(sender, exception, **extra): sender.logger.debug('Got exception during processing: %s', exception)from flask import got_request_exceptiongot_request_exception.connect(log_exception, app)flask.request_tearing_down
This signal is sent when the request crashes, whether or not an exception is thrown. Currently, a function that listens to this signal is called after a crashed processor, but nothing is available.
Subscription example:
def close_db_connection(sender, **extra): session.close()from flask import appcontext_tearing_downrequest_tearing_down.connect(close_db_connection, app)
In Flask 0.9, this will also pass an exc keyword parameter, if this parameter exists. This parameter is a reference to an exception that causes a crash.
3. flask. appcontext_tearing_down
This signal is sent when the application environment crashes. This signal is always sent, even because of a crash caused by an exception. The function that listens to this signal will be called after the processor crashes normally, but you cannot return this signal.
Subscription example:
def close_db_connection(sender, **extra): session.close()from flask import request_tearing_downappcontext_tearing_down.connect(close_db_connection, app)
This will also pass an exc keyword parameter, if this parameter exists. This parameter is a reference to an exception that causes a crash.
4. flask. appcontext_pushed
When an application environment is pressed, the application sends this signal. This signal is usually used to temporarily hook information in unit tests. For example, it can be used to change the existing resources in the g object.
Usage example:
from contextlib import contextmanagerfromflask import appcontext_pushed@contextmanagerdef user_set(app, user): def handler(sender, **kwargs): g.user = user with appcontext_pushed.connected_to(handler, app): yield
Write in the test code as follows:
def test_user_me(self): with user_set(app, 'john'): c = app.test_client() resp = c.get('/users/me') assert resp.data == 'username=john'New in version 0.10.
5. appcontext_popped
When an application environment pops up, the application sends this signal. This signal is usually written as the appcontext_tearing_down signal.
6. flask. message_flashed
This signal is sent when an application emits a message. The message parameter is the message content, and the 'category parameter is the message category.
Subscription example:
recorded = []def record(sender, message, category, **extra): recorded.append((message, category))from flask import message_flashedmessage_flashed.connect(record, app)
Summary
Signals allow you to securely subscribe to them in an instant. For example, these temporary subscriptions are very helpful for testing. When using signals, do not cause exceptions to the signal subscriber (receiver) because exceptions may interrupt the program.