Created
May 29, 2019 11:39
-
-
Save browniebroke/9e41b8eec3bdf87b0d360bc0bd4d8e2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Custom Celery task for providing useful extensions | |
http://docs.celeryproject.org/en/latest/userguide/tasks.html#custom-task-classes | |
""" | |
from celery.app.task import Task | |
from django.db import transaction | |
class BetterCeleryTask(Task): | |
"""Extend the default Task class to add helpers with Django's on_commit().""" | |
def delay_on_commit(self, *args, **kwargs): | |
return transaction.on_commit(lambda: self.delay(*args, **kwargs)) | |
def apply_async_on_commit(self, *args, **kwargs): | |
return transaction.on_commit(lambda: self.apply_async(*args, **kwargs)) | |
# use it per task as follows: | |
@app.task(base=BetterCeleryTask) | |
def some_task(some_item_pk): | |
item = Item.objects.get(pk=some_item_pk) | |
print(item.name) | |
# or for the whole app, in which case all your tasks will use it | |
celery_app = celery.Celery( | |
"your_app_name", | |
task_cls="your.python.path:BetterCeleryTask", | |
) | |
# And use your taks as follows | |
some_task.delay_on_commit(123) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment