交易。原子芹菜任务
我有事务。原子芹菜任务:
@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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从技术上讲,
do不打开一个新的连接,它会从transaction.atomic
atmicdjango.db.connections
集合中获取现有连接,并且这些连接通常在启动时进行实例化。连接保持生命,并在整个应用程序中重复使用。通常,在执行查询以确保连接可用之前,所有连接都进行ping
(否则将建立新的连接)。退出任务的代码块将无法关闭连接,并且根据您的连接设置,将在重述该过程时发生相同的过程(transaction.atomic
将从Connections 集合,然后执行查询将进行连接检查)。
Technically,
transaction.atomic
does not open a new connection, it grabs an existing connection out of thedjango.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 aping
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 theconnections
collection and then the execution of the query will do the connectivity check).