Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import requests
- from django.conf import settings
- from requests.exceptions import RequestException
- from celery import shared_task
- from celery.exceptions import SoftTimeLimitExceeded
- class PendingTaskException(Exception):
- """ There are pending tasks """
- pass
- @shared_task(
- bind = True,
- autoretry_for = (
- RequestException,
- SoftTimeLimitExceeded,
- PendingTaskException
- ),
- soft_time_limit = 60,
- retry_backoff = 3,
- max_retries = 1000
- )
- def notify(self, action, payload):
- from .models import Task, Delivery
- hook_backend = getattr(settings,'HOOK_BACKEND', None)
- if hook_backend:
- task, created = Task.objects.get_or_create(
- task_id = self.request.id,
- action = action,
- defaults={
- 'payload': payload
- }
- )
- # check for pending tasks
- pending = Task.objects.filter(created__lt=task.created, success=False).exclude(pk=task.pk).count()
- if pending:
- raise PendingTaskException('Wait for pending taks')
- data = {
- 'action': action,
- 'payload': payload
- }
- # start delivery
- delivery = Delivery.objects.create(task = task)
- r = requests.post(hook_backend, json=data)
- delivery.response_status = r.status_code
- delivery.response_message = r.content
- delivery.save()
- if r.status_code == 200:
- task.success = True
- task.save()
- else:
- raise RequestException()
- return data
- return None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement