Created
December 7, 2016 02:27
-
-
Save hustshawn/74c008a7866ba6b3b6f5f17e80ab29a2 to your computer and use it in GitHub Desktop.
A django signal working flow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
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
Reference: http://www.shutupandship.com/2012/04/django-signals-and-observer-design.html