[英]Calling transaction.commit() inside commit_on_success block in Django
我有這樣的代碼:
@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)
這是否符合我的預期,即:
transaction.commit()
執行提交 do_stuff()
引發異常,則事務將回滾 我使用的是Django 1.4和MySQL。
如果視圖正常返回,則transaction.commit_on_success()
將提交,如果引發異常,則中止。 在您的情況下,它應該“有效”,但可能不是最佳解決方案-由於您仍然必須手動提交,因此使用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.