Showing posts with label signals. Show all posts
Showing posts with label signals. Show all posts

Oct 11, 2011

Making Django's signals asynchronous with Celery

from celery.task import task
from django.db.models.signals import post_save

from myproject.models import MyModel

# Warning. Monkey patch.
from django.dispatch.dispatcher import Signal
def reducer(self):
    return (Signal, (self.providing_args,))
Signal.__reduce__ = reducer

# With the patch done, we can now connect to celery tasks.
@task(ignore_result=True)
def async_post_save(sender, instance, **kwargs):
    # do something with the instance.
    pass
post_save.connect(async_post_save.delay, sender=MyModel)
Патч нужен только если требуется в декоратор task передавать аргумент(ы). В противном случае достаточно:
from celery.task import task
from django.db.models.signals import post_save

from myproject.models import MyModel

@task
def async_post_save(instance):
    # do something with the instance.
    pass

def post_save_reciever(sender, instance, **kwargs):
    async_post_save.delay()
post_save.connect(post_save_reciever)
Оригинал в блоге  Dougal Matthews

Oct 5, 2011

Signals registration

Best place for Django signals is app/signals.py file. This snippet imports signal modules from all installed apps.
from importlib import import_module
from django.conf import settings

for app in settings.INSTALLED_APPS:
    try:
        import_module( 'signals', app)
    except ImportError as e:
        print 'Failed to import "%s", reason: %s' % (app, str(e)))
Original: http://djangosnippets.org/snippets/2561/