【问题标题】:Django: How to rollback (@transaction.atomic) without raising exception?Django:如何在不引发异常的情况下回滚(@transaction.atomic)?
【发布时间】:2017-01-12 21:47:39
【问题描述】:

我正在使用 Django 的命令来执行一些涉及数据库操作的任务:

class SomeCommand(BaseCommand):
    @transaction.atomic
    def handle(self, *args, **options):
        # Some stuff on the database

如果在我的程序执行期间抛出异常,@transaction.atomic 保证回滚。我可以强制这种行为而不抛出异常吗?比如:

# Doing some stuff, changing objects

if some_condition:
    # ABANDON ALL CHANGES AND RETURN

【问题讨论】:

  • 我怀疑没有办法做到这一点。您将不得不提出异常并安静地捕获它。我创建了一个临时异常子类,将其捕获并通过,全部在 atomic 块内。

标签: django


【解决方案1】:

transaction.set_rollback 可以做到这一点。

class SomeCommand(BaseCommand):
    @transaction.atomic
    def handle(self, *args, **options):
        # Doing some stuff, changing objects
        if some_condition:
            # Return, rolling back transaction when atomic block exits
            transaction.set_rollback(True)
            return

引用the docs:

将回滚标志设置为True 会在退出最里面的原子块时强制回滚。这对于触发回滚而不引发异常可能很有用。

【讨论】:

    【解决方案2】:

    只需致电transaction.rollback()

    调用 transaction.rollback() 会回滚整个事务。任何未提交的数据库操作都将丢失。

    您可以在docs 中查看示例。

    【讨论】:

    • 禁止将transaction.rollback()transaction@atomic一起使用,所以如果某个地方确实抛出了异常,则不会发生回滚。
    • 不仅如此,django 在transaction.atomic 块内调用rollback() 时会抛出错误。这根本不是解决方案。
    • 扩展 @reformy 所说的内容,来自文档:In order to guarantee atomicity, atomic disables some APIs. Attempting to commit, roll back, or change the autocommit state of the database connection within an atomic block will raise an exception.
    【解决方案3】:

    您可以管理代码执行以引发或不引发异常:

    try:
        if some_condition:
            with transaction.atomic():
                # Your logic here
    except Exception, e:  # An example, use a explicit error
        # Show something friendly instead of a exception
    

    【讨论】:

    • 在这段代码中,“你的逻辑”部分将提交给 DB。这里没有回滚。
    • 我看不出你是在哪个平行宇宙中观察到的。我一直在使用相同的方法,它可以在异常引发时回滚事务时按预期工作。
    猜你喜欢
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多