交易。原子芹菜任务

发布于 2025-01-31 21:41:36 字数 637 浏览 0 评论 0原文

我有事务。原子芹菜任务:

@app.task(
    name="create_order",
    bind=True,
    ignore_results=True,
)
@transaction.atomic
def create_order(self: Task) -> None:
    
    try:
        data = MyModel.objects.select(...)
        # Some actions that may take long time and only use DB for SELECT queries 
        make_order(data, ...)
    except SomeException as exc:
        raise self.retry(exc=exc, countdown=5)
    else:
        data.status = DONE
        data.save()

@transaction.atomic装饰器与DB创建新连接,并在任何例外或提交语句之前保持它。但是,如果任务提高self.retry,该怎么办?连接将被关闭,而任务重新恢复时将打开新的连接?

I have transaction.atomic celery task:

@app.task(
    name="create_order",
    bind=True,
    ignore_results=True,
)
@transaction.atomic
def create_order(self: Task) -> None:
    
    try:
        data = MyModel.objects.select(...)
        # Some actions that may take long time and only use DB for SELECT queries 
        make_order(data, ...)
    except SomeException as exc:
        raise self.retry(exc=exc, countdown=5)
    else:
        data.status = DONE
        data.save()

@transaction.atomic decorator creates new connection with DB and holds it before any exception or COMMIT statement. But what if task raises self.retry? Connection will be closed and when the task retries django will open a new one?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心凉怎暖 2025-02-07 21:41:36

从技术上讲, transaction.atomic atmic do不打开一个新的连接,它会从django.db.connections集合中获取现有连接,并且这些连接通常在启动时进行实例化。连接保持生命,并在整个应用程序中重复使用。通常,在执行查询以确保连接可用之前,所有连接都进行ping(否则将建立新的连接)。退出任务的代码块将无法关闭连接,并且根据您的连接设置,将在重述该过程时发生相同的过程(transaction.atomic将从Connections 集合,然后执行查询将进行连接检查)。

Technically, transaction.atomic does not open a new connection, it grabs an existing connection out of the django.db.connections collection, and these connections are typically instantiated at startup. The connections stay live and are reused across the app. Typically, all of the connections do a ping before executing a query to make sure the connection is usable (otherwise a new connection will be established). Exiting the code block of the task will not close the connection, and depending on your connection settings, the same process will happen when the process is retried (transaction.atomic will grab the connection out of the connections collection and then the execution of the query will do the connectivity check).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文