Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Signals in django

Roberto
January 17, 2013
96

Signals in django

A (very) short introduction on the use of signals in django.

Roberto

January 17, 2013
Tweet

Transcript

  1. What they are “In a nutshell, signals allow certain senders

    to notify a set of receivers that some action has taken place. They’re especially useful when many pieces of code may be interested in the same events.” http://docs.djangoproject.com
  2. How they work (recieving) Listening to a signal: Signal.connect(receiver[, sender=None,

    weak=True, dispatch_uid=None]) reciever can be any python function or method. Listeners in action: from django.db.models.signals import pre_save from django.dispatch import receiver from myapp.models import MyModel @receiver(pre_save, sender=MyModel) def my_handler(sender, **kwargs): ... Signals are synchronous: Request is therefore blocked until each signal has finished processing. Do not use them to perform long calculations or I/O.
  3. How they work (creating and sending) Defining signals: import django.dispatch

    pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"]) Sending a signal: class PizzaStore(object): ... def send_pizza(self, toppings, size): pizza_done.send(sender=self, toppings=toppings, size=size) ...