I have code like:
@transaction.commit_on_success()
def foo():
# Performs various database operations and may raise exception
do_stuff()
my_object = MyModel.objects.create()
# Commit transaction so Celery task will see the newly created object
transaction.commit()
# Async call Celery task that does something with the new object
my_celery_task.delay(my_object.id)
Does this do what I expect it to do, ie:
transaction.commit()
performs commit do_stuff()
raises exception, transaction is rolled back I'm on Django 1.4 and MySQL.
Yes. According to Django docs:
If the function returns successfully, then Django will commit all work done within the function at that point. If the function raises an exception, though, Django will roll back the transaction.
From here
transaction.commit_on_success()
will commit if the view returns normally, and abort if an exception is raised. In your case, it should "work" but is possibly not the best solution - since you have to manually commit anyway, you'd probably be better using transaction.commit_manually()
( https://docs.djangoproject.com/en/1.4/topics/db/transactions/#django.db.transaction.commit_manually ):
@transaction.commit_manually()
def foo():
try:
# Performs various database operations and may raise exception
do_stuff()
my_object = MyModel.objects.create()
except Exception, e:
# oops, let's forget about it
transaction.rollback()
raise
else:
# Commit transaction so Celery task will see the newly created object
transaction.commit()
# Async call Celery task that does something with the new object
my_celery_task.delay(my_object.id)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.