Skip to content

Instantly share code, notes, and snippets.

@dokterbob
Created March 30, 2011 09:25
Show Gist options
  • Save dokterbob/894118 to your computer and use it in GitHub Desktop.
Save dokterbob/894118 to your computer and use it in GitHub Desktop.
Class-based listeners, based on Django's class-based generic views.
class Listener(object):
"""
Class-based listeners, based on Django's class-based generic views. Yay!
Usage::
class MySillyListener(Listener):
def dispatch(self, sender, **kwargs):
# DO SOMETHING
pass
funkysignal.connect(MySillyListener.as_view(), weak=False)
"""
def __init__(self, **kwargs):
"""
Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.
"""
# Go through keyword arguments, and either save their values to our
# instance, or raise an error.
for key, value in kwargs.iteritems():
setattr(self, key, value)
@classonlymethod
def as_listener(cls, **initkwargs):
"""
Main entry point for a sender-listener process.
"""
# sanitize keyword arguments
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError(u"You tried to pass in the %s method name as a "
u"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError(u"%s() received an invalid keyword %r" % (
cls.__name__, key))
def listener(sender, **kwargs):
self = cls(**initkwargs)
return self.dispatch(sender, **kwargs)
# take name and docstring from class
update_wrapper(listener, cls, updated=())
# and possible attributes set by decorators
update_wrapper(listener, cls.dispatch, assigned=())
return listener
def dispatch(self, sender, **kwargs):
raise NotImplementedError('Sublcasses should implement this!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment