Skip to content

Instantly share code, notes, and snippets.

@tapanpandita
Created October 8, 2016 03:56
Show Gist options
  • Save tapanpandita/46d2e2f63c7425547a865cb6298a172f to your computer and use it in GitHub Desktop.
Save tapanpandita/46d2e2f63c7425547a865cb6298a172f to your computer and use it in GitHub Desktop.
Transaction aware celery abstract task
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))
@luiscastillocr
Copy link

luiscastillocr commented Oct 10, 2018

class TransactionAwareTask(Task):
    '''
    Task class which is aware of Django DB transactions and
    only executes tasks after the transaction has been committed
    '''
    
    abstract = True

    def apply_async(self, *args, **kwargs):
        cnx = transaction.get_connection()
        if not cnx.in_atomic_block:
            # https://medium.com/gitux/speed-up-django-transaction-hooks-tests-6de4a558ef96
            return super(TransactionAwareTask, self).apply_async(*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))

I would like to contribute with some few code lines, the idea is to make it work with transactional and not transactional tests

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment