Skip to content

Instantly share code, notes, and snippets.

@zacharyvoase
Created March 15, 2009 04:02
Show Gist options
  • Save zacharyvoase/79303 to your computer and use it in GitHub Desktop.
Save zacharyvoase/79303 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
#
# Copyright (c) 2009 Zachary Voase
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
from functools import wraps
from django.db.models import *
VALID_SIGNALS = ['pre_init',
'post_init',
'pre_save',
'post_save',
'pre_delete',
'post_delete']
class InvalidSignalError(Exception):
pass
class ModelSignals(object):
def __init__(self, model):
self.model = model
def connect(self, signal_name):
"""Generates a decorator to connect signal handlers."""
if signal_name not in VALID_SIGNALS:
raise InvalidSignalError
def decorator(function):
@wraps(function)
def wrapper(*args, **kwargs):
# Remove the 'sender' kwarg because we already know what that is.
kwargs.pop('sender', None)
if 'instance' in kwargs:
args = (kwargs.pop('instance'),) + args
return function(*args, **kwargs)
getattr(signals, signal_name).connect(wrapper, sender=self.model)
return wrapper
decorator.__name__ = signal_name
return decorator
def __getattribute__(self, attribute):
try:
return object.__getattribute__(self, attribute)
except AttributeError:
if attribute in VALID_SIGNALS:
return self.connect(attribute)
@classmethod
def contribute_to_class(cls, class_, name):
setattr(class_, name, cls(class_))
class ModelWithSignalsBase(base.ModelBase):
def __new__(cls, name, bases, attrs):
model = super(ModelWithSignalsBase, cls).__new__(cls, name, bases, attrs)
model.add_to_class('signals', ModelSignals)
return model
class ModelWithSignals(Model):
__metaclass__ = ModelWithSignalsBase
class Meta(object):
abstract = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment