webhooks.py 1.9 KB

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