Flask

Signals

Remarks#

Flask supports signals using Blinker. Signal support is optional; they will only be enabled if Blinker is installed.

pip install blinker

https://flask.pocoo.org/docs/dev/signals/


Signals are not asynchronous. When a signal is sent, it immediately executes each of the connected functions sequentially.

Connecting to signals

Use a signal’s connect method to connect a function to a signal. When a signal is sent, each connected function is called with the sender and any named arguments the signal provides.

from flask import template_rendered

def log_template(sender, template, context, **kwargs):
    sender.logger.info(
        'Rendered template %(template)r with context %(context)r.',
        template=template, context=context
    )

template_rendered.connect(log_template)

See the documentation on built-in signals for information about what arguments they provides. A useful pattern is adding a **kwargs argument to catch any unexpected arguments.

Custom signals

If you want to create and send signals in your own code (for example, if you are writing an extension), create a new Signal instance and call send when the subscribers should be notified. Signals are created using a Namespace.

from flask import current_app
from flask.signals import Namespace

namespace = Namespace()
message_sent = namespace.signal('mail_sent')

def message_response(recipient, body):
    ...
    message_sent.send(
        current_app._get_current_object(),
        recipient=recipient,
        body=body
    )

@message_sent.connect
def log_message(app, recipient, body):
    ...

Prefer using Flask’s signal support over using Blinker directly. It wraps the library so that signals remain optional if developers using your extension have not opted to install Blinker.


This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow