[英]Calling transaction.commit() inside commit_on_success block in Django
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 transaction.commit()
执行提交 do_stuff()
raises exception, transaction is rolled back do_stuff()
引发异常,则事务将回滚 I'm on Django 1.4 and MySQL. 我使用的是Django 1.4和MySQL。
Yes. 是。 According to Django docs:
根据Django文档:
If the function returns successfully, then Django will commit all work done within the function at that point.
如果函数成功返回,那么Django将在此时提交在函数内完成的所有工作。 If the function raises an exception, though, Django will roll back the transaction.
但是,如果函数引发异常,Django将回滚事务。
transaction.commit_on_success()
will commit if the view returns normally, and abort if an exception is raised. 如果视图正常返回,则
transaction.commit_on_success()
将提交,如果引发异常,则中止。 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()
( 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.