Login

Execute a signal once

Author:
johnnoone
Posted:
May 5, 2009
Language:
Python
Version:
1.0
Tags:
decorator signals once
Score:
3 (after 3 ratings)

Decorates signals for executing only one time

Exemple usage :

from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.contrib.auth.models import User

@one
def user_welcome(sender, instance, created, **kwargs):
    # Send a welcome email
    if created == True and isinstance(instance, User):
        instance.message_set.create(message=_(u"Ho, Welcome %s!" % instance))
        subject, from_email, to = 'Welcome !', 'from@example.com', instance.email
        text_content = render_to_string('mail/welcome.html', { 'user': instance })
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.send()
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from functools import wraps

def one(func=None):
    """decorates signals for executing only one time
    
    Exemple Usage --
    
    from django.core.mail import EmailMultiAlternatives
    from django.template.loader import render_to_string
    from django.contrib.auth.models import User
    
    @one
    def user_welcome(sender, instance, created, **kwargs):
        # Send a welcome email
        if created == True and isinstance(instance, User):
            instance.message_set.create(message=_(u"Ho, Welcome %s!" % instance))
            subject, from_email, to = 'Welcome !', 'from@example.com', instance.email
            text_content = render_to_string('mail/welcome.html', { 'user': instance })
            msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
            msg.send()
    
    """
    
    E = '_exec_one_time'
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            instance = kwargs['instance']
            e = getattr(instance, E, [])
            c = func.__name__
            if c not in e:
                e.append(c)
                setattr(instance, E, e)
                return func(*args, **kwargs)
        except:
            return func(*args, **kwargs)
    return wrapper

More like this

  1. Create multiple related objects at once by yaniv.haber 6 years, 1 month ago
  2. Signal to notify new saved comments by arthurfurlan 5 years, 11 months ago
  3. PatchModelForm - A ModelForm subclass with the semantics of the PATCH HTTP method by gnrfan 2 years, 12 months ago
  4. Decorator to execute a method only once by atodorov-otb 1 year, 5 months ago
  5. group_required decorator by msanders 5 years, 9 months ago

Comments

Please login first before commenting.