-->

Defining and sending django signals

By: Priya Philip 1 month ago

Defining signals

class Signal(providing_args=list)

All signals are  django.dispatch.Signal instances. The providing_args is a list of the names of arguments the signal will provide to listeners.

This is purely documentational, however, as there is nothing that checks that the signal actually provides these arguments to its listeners.

For example:

import django.dispatch

pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])

This declares a pizza_done signal that will provide receivers with toppings and size arguments.

Remember that you’re allowed to change this list of arguments at any time, so getting the API right on the first try isn’t necessary.

Sending signals

There are two ways to send signals in Django.

Signal.send(sender, **kwargs)
Signal.send_robust(sender, **kwargs)

To send a signal, call either Signal.send() (all built-in signals use this) or Signal.send_robust().

You must provide the sender argument (which is a class most of the time) and may provide as many other keyword arguments as you like.

For example, here’s how sending our pizza_done signal might look:

class PizzaStore:
    ...

    def send_pizza(self, toppings, size):
        pizza_done.send(sender=self.__class__, toppings=toppings, size=size)
        ...

Both send() and send_robust() return a list of tuple pairs [(receiver, response), ... ], representing the list of called receiver functions and their response values.

send() differs from send_robust() in how exceptions raised by receiver functions are handled.

 send() doesnot catch any exceptions raised by receivers; it simply allows errors to propagate. Thus not all receivers may be notified of a signal in the face of an error.

send_robust() catches all errors derived from Python’s Exception class, and ensures all receivers are notified of the signal. If an error occurs, the error instance is returned in the tuple pair for the receiver that raised the error.

The tracebacks are present on the __traceback__ attribute of the errors returned when calling send_robust().

Disconnecting signals

Signal.disconnect(receiver=None, sender=None, dispatch_uid=None)

To disconnect a receiver from a signal, call Signal.disconnect(). The arguments are as described in Signal.connect(). The method returns True if a receiver was disconnected and False if not.

The receiver argument indicates the registered receiver to disconnect. It may be None if dispatch_uid is used to identify the receiver.

Comments

Wish to hire us?

We take the vision which comes from dreams and apply the magic of science and mathematics, adding the heritage of our profession and our knowledge to create a design.