The signals signaling mechanism in the flask framework of Python

Source: Internet
Author: User
Flask provides a signal (signals) function, which is a message distribution mechanism. Similar to hooks (Hooks). Using the signal function can reduce the coupling of the program and decompose the complex business model. For example, after updating the product data, you can send a signal. When there is a function to process the product data, the signal can be captured for processing. For example, to create a product cache, or to update the search index.

Defining the Signal

The Flask signal function uses the Blinker module, so the Blinker module needs to be installed first

Pip Install Blinker

Define a signal:

From blinker Import namespaceproduct_saved = Namespace ()

You can also use the Flask wrapped singles object:

From Flask.singles import Namespace

Send Signal

Send the signal with the app instance method, as shown in the following example:

Product_saved.send (app, product=product)

You can add parameters to be passed after the app, but must be in name=value format and not support the use of a single variable name.

Pick up Signal

The Connect_via adorner function can be used to receive signals:

@product_saved. Connect_via (APP) def updatecache (app, product):  print (product)

The Flask has the following core signals:

1.flask.template_rendered

This signal is sent after a template has been rendered successfully. The signal-passing template is an instance of the templates, and the context is an environment object that is a dictionary.

Sample subscription:

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 setting is complete. Because the request environment is already bound, subscribers can use a standard global proxy, such as request, to manipulate requests.

Sample subscription:

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 the response is sent to the client. The response of the signal transmission is the response that will be sent.

Sample subscription:

def log_response (sender, Response, **extra):  sender.logger.debug (' Request context is about to close. '            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 is sent earlier than standard exception handling. In debug mode, this signal is also sent when an exception occurs, although there is no exception handling. The exception of the signal transmission is the exception object.

Sample subscription:

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, regardless of whether an exception is thrown. Currently, the function that listens for this signal is called after a general crash processor, but nothing is available.

Sample subscription:

def close_db_connection (sender, **extra):  session.close () from flask import Appcontext_tearing_downrequest_ Tearing_down.connect (close_db_connection, app)

In Flask version 0.9, this also passes a exc keyword argument if the parameter exists. This parameter is a reference to the exception that caused the 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 for this signal is called after the regular crash handler, but you cannot give back the signal.

Sample subscription:

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 a exc keyword argument if the parameter exists. This parameter is a reference to the exception that caused the crash.

4.flask.appcontext_pushed

When an application's environment is pressed in, the application sends the signal. This signal is typically used to temporarily hook up information in a unit test. For example, it can be used to change existing resources in G objects.

Usage examples:

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

In the test code, write this:

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 app's environment is ejected, the app sends this signal. This signal is usually written as a appcontext_tearing_down signal.

6.flask.message_flashed

This signal is emitted when the app flashes a message. The message ' parameter is the content of the messages, ' category parameter is the message class.

Sample subscription:

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 subscribe to them safely in a flash. For example, these temporary subscriptions are useful for testing. When using a signal, do not let the Subscriber (receiver) of the signal have an exception because the exception causes the program to break.

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.