webhooks.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import datetime
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.db.models import Q
  4. from extras.models import Webhook
  5. from extras.constants import OBJECTCHANGE_ACTION_CREATE, OBJECTCHANGE_ACTION_DELETE, OBJECTCHANGE_ACTION_UPDATE
  6. from utilities.api import get_serializer_for_model
  7. def enqueue_webhooks(instance, action):
  8. """
  9. Find Webhook(s) assigned to this instance + action and enqueue them
  10. to be processed
  11. """
  12. type_create = action == OBJECTCHANGE_ACTION_CREATE
  13. type_update = action == OBJECTCHANGE_ACTION_UPDATE
  14. type_delete = action == OBJECTCHANGE_ACTION_DELETE
  15. # Find assigned webhooks
  16. obj_type = ContentType.objects.get_for_model(instance.__class__)
  17. webhooks = Webhook.objects.filter(
  18. Q(enabled=True) &
  19. (
  20. Q(type_create=type_create) |
  21. Q(type_update=type_update) |
  22. Q(type_delete=type_delete)
  23. ) &
  24. Q(obj_type=obj_type)
  25. )
  26. if webhooks:
  27. # Get the Model's API serializer class and serialize the object
  28. serializer_class = get_serializer_for_model(instance.__class__)
  29. serializer_context = {
  30. 'request': None,
  31. }
  32. serializer = serializer_class(instance, context=serializer_context)
  33. # We must only import django_rq if the Webhooks feature is enabled.
  34. # Only if we have gotten to ths point, is the feature enabled
  35. from django_rq import get_queue
  36. webhook_queue = get_queue('default')
  37. # enqueue the webhooks:
  38. for webhook in webhooks:
  39. webhook_queue.enqueue(
  40. "extras.webhooks_worker.process_webhook",
  41. webhook,
  42. serializer.data,
  43. instance.__class__,
  44. action,
  45. str(datetime.datetime.now())
  46. )