【问题标题】:Calling transaction.commit() inside commit_on_success block in Django在 Django 的 commit_on_success 块内调用 transaction.commit()
【发布时间】:2014-12-05 08:58:07
【问题描述】:

我有这样的代码:

@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。

【问题讨论】:

    标签: python mysql django celery


    【解决方案1】:

    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)
    

    【讨论】:

      【解决方案2】:

      是的。根据 Django 文档:

      如果函数成功返回,那么 Django 将提交所有工作 此时在函数内完成。如果函数引发 异常,但是,Django 将回滚事务。

      来自here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-18
        • 1970-01-01
        • 1970-01-01
        • 2010-11-22
        相关资源
        最近更新 更多