Skip to content

Instantly share code, notes, and snippets.

@tapanpandita
Last active February 10, 2021 06:22
Show Gist options
  • Save tapanpandita/a84938354d32b0f12423d69259e06c2c to your computer and use it in GitHub Desktop.
Save tapanpandita/a84938354d32b0f12423d69259e06c2c to your computer and use it in GitHub Desktop.
A celery abstract task class that is fired when a transaction is committed
class TransactionAwareTask(Task):
'''
Task class which is aware of django db transactions and only executes tasks
after transaction has been committed
'''
abstract = True
def apply_async(self, *args, **kwargs):
'''
Unlike the default task in celery, this task does not return an async
result
'''
transaction.on_commit(
lambda: super(TransactionAwareTask, self).apply_async(
*args, **kwargs))
@shared_task(base=TransactionAwareTask, bind=True, max_retries=settings.EVENT_MAX_RETRIES)
def push_event(self, event_id):
event = Event.objects.get(id=event_id)
# code to push webhook
@shared_task(bind=True, max_retries=settings.EVENT_MAX_RETRIES)
def push_event(self, event_id):
event = Event.objects.get(id=event_id)
# code to push webhook
with transaction.atomic():
# update task
# update driver
event = Event.objects.create(...)
push_event.delay(event.id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment