Skip to content

Instantly share code, notes, and snippets.

@hustshawn
Created December 7, 2016 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hustshawn/74c008a7866ba6b3b6f5f17e80ab29a2 to your computer and use it in GitHub Desktop.
Save hustshawn/74c008a7866ba6b3b6f5f17e80ab29a2 to your computer and use it in GitHub Desktop.
A django signal working flow
from dispatch import Signal
# The Signal object (think of it as an exchange)
log_it = Signal(providing_args=['level', 'message'])
# These functions are receivers (subscribers). They will receive
# the signal (message) sent (published) by the sender (publisher).
def simple_receiver(**kwargs):
message, level = kwargs['message'], kwargs['level']
print 'Receiver # 1'
print '\tLevel: %d, Message: %s\n' % (level, message)
def picky_receiver(**kwargs):
message, level = kwargs['message'], kwargs['level']
print 'Receiver # 2'
if level < 2:
print "\tSome unimportant message was sent. Ignoring it!\n"
# Okay, now time to connect these receivers to the log_it signal object.
log_it.connect(simple_receiver)
log_it.connect(picky_receiver)
# The sender (publisher) that sends (publishes) a signal (message).
# This message will received by all connected (subscribed)
# receivers (subscribers).
def a_cool_sender():
# Do something cool here
# Now send a signal to all receivers
log_it.send(sender='a_cool_sender', message='Hello!', level=1)
a_cool_sender()
@hustshawn
Copy link
Author

@hustshawn
Copy link
Author

hustshawn commented Dec 7, 2016

The signal creation and receiver callback is not that difficult to understand, but when sending a signal, the sender arguments in the Signal.send(sender, **kwargs) function can be either the instance of a class or the function name if it is called inside a function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment