Debian Codegraph @

celery_haystack/signals.py

raw symbols SCIP
1 from django.db import transaction
2 from django.db.models import signals
3
4 from haystack.signals import RealtimeSignalProcessor
5 from haystack.exceptions import NotHandled
6 from haystack.utils import get_identifier
7
8 from .conf import settings
9 from .utils import get_update_task
10 from .indexes import CelerySearchIndex
11
12
13 class CelerySignalProcessor(RealtimeSignalProcessor):
14 def __init__(self, *args, **kwargs):
15 super().__init__(*args, **kwargs)
16 self._queue = []
17 self._on_commit_registered = False
18
19 def handle_save(self, sender, instance, **kwargs):
20 return self.enqueue('update', instance, sender, **kwargs)
21
22 def handle_delete(self, sender, instance, **kwargs):
23 return self.enqueue('delete', instance, sender, **kwargs)
24
25 def run_task(self):
26 options = {}
27 if settings.CELERY_HAYSTACK_QUEUE:
28 options['queue'] = settings.CELERY_HAYSTACK_QUEUE
29 if settings.CELERY_HAYSTACK_COUNTDOWN:
30 options['countdown'] = settings.CELERY_HAYSTACK_COUNTDOWN
31
32 if self._queue:
33 task = get_update_task()
34 task.apply_async((self._queue,), {}, **options)
35
36 self._queue = []
37
38
39 def enqueue(self, action, instance, sender, **kwargs):
40 """
41 Given an individual model instance, determine if a backend
42 handles the model, check if the index is Celery-enabled and
43 enqueue task.
44 """
45 using_backends = self.connection_router.for_write(instance=instance)
46
47 for using in using_backends:
48 try:
49 connection = self.connections[using]
50 index = connection.get_unified_index().get_index(sender)
51 except NotHandled:
52 continue # Check next backend
53
54 if isinstance(index, CelerySearchIndex):
55 if action == 'update' and not index.should_update(instance):
56 continue
57 self._queue.append((action, get_identifier(instance)))
58
59 if not self._on_commit_registered:
60 transaction.on_commit(self.run_task)