Advertisement
Guest User

Untitled

a guest
Jan 27th, 2020
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. import requests
  2.  
  3. from django.conf import settings
  4.  
  5. from requests.exceptions import RequestException
  6.  
  7. from celery import shared_task
  8. from celery.exceptions import SoftTimeLimitExceeded
  9.  
  10.  
  11. class PendingTaskException(Exception):
  12.     """ There are pending tasks """
  13.     pass
  14.  
  15.  
  16. @shared_task(
  17.     bind = True,
  18.     autoretry_for = (
  19.         RequestException,
  20.         SoftTimeLimitExceeded,
  21.         PendingTaskException
  22.     ),
  23.     soft_time_limit = 60,
  24.     retry_backoff = 3,
  25.     max_retries = 1000
  26. )
  27. def notify(self, action, payload):
  28.     from .models import Task, Delivery
  29.     hook_backend = getattr(settings,'HOOK_BACKEND', None)
  30.  
  31.     if hook_backend:
  32.  
  33.         task, created = Task.objects.get_or_create(
  34.             task_id = self.request.id,
  35.             action = action,
  36.             defaults={
  37.                 'payload': payload
  38.             }
  39.         )
  40.  
  41.         # check for pending tasks
  42.         pending = Task.objects.filter(created__lt=task.created, success=False).exclude(pk=task.pk).count()
  43.         if pending:
  44.             raise PendingTaskException('Wait for pending taks')
  45.  
  46.         data = {
  47.             'action': action,
  48.             'payload': payload
  49.         }
  50.  
  51.         # start delivery
  52.         delivery = Delivery.objects.create(task = task)
  53.  
  54.        
  55.         r = requests.post(hook_backend, json=data)
  56.         delivery.response_status = r.status_code
  57.         delivery.response_message = r.content
  58.         delivery.save()
  59.  
  60.         if r.status_code == 200:
  61.             task.success = True
  62.             task.save()
  63.         else:
  64.             raise RequestException()
  65.        
  66.         return data
  67.     return None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement