在Django中的事务提交后运行代码

编程入门 行业动态 更新时间:2024-10-27 04:34:14
本文介绍了在Django中的事务提交后运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要向rabbitmq服务器发送一些消息以进行离线处理,但是消息会得到在Django事务被提交之前给消费者。

我的消息是在模型的post_save信号中发送的。我正在寻找的是一个类似的机制,使用信号或其他东西,将在提交后执行代码(如果事务失败,则不执行任何操作)。

I在Django中没有找到任何通用的方法。你有什么想法吗?

解决方案

更新2 :django-transaction-hooks是合并到Django核心并在Django版本中发布1.9。

更新: django-transaction-hooks 解决了这个问题。

我不相信有一个干净的方法来做到这一点;至少我不能想到一个。您可以使用monkeypatch django.db.transactionmit发送自定义信号;不太漂亮,但我认为这样会有效。

也可以在 django-developers邮件列表。开发人员通常厌恶添加新的信号,但您可能在这里有一个很好的例子(从核心开发人员的反驳可能包括一个有用的建议如何解决您的情况)。不过,如果您等到1.1出来之后,您可能会收到回复。

Is there any way to run some code after transaction commit in Django?

I need to send some messages to a rabbitmq server for offline processing, but the message gets to the consumer before the Django transaction is commited.

My message is sent in the post_save signal of the model. What I'm looking for is a similar mechanism, using signals or something else, that would execute code after the commit (and do nothing if the transaction fails).

I haven't found any generic way of doing it in Django. Do you have any ideas?

解决方案

UPDATE 2: django-transaction-hooks was merged into Django core and released in Django version 1.9.

UPDATE: django-transaction-hooks solves this problem.

I don't believe there is a clean way to do this; at least I can't think of one. You could monkeypatch django.db.transactionmit to send a custom signal; not pretty but I think it would work.

Might also be interesting to raise this use-case on the django-developers mailing list. The devs are generally averse to adding new signals, but you might have a good case here (and a rebuttal from a core dev might include a useful suggestion of how to resolve your situation). You're more likely to get responses if you wait until after 1.1 comes out, though.

更多推荐

在Django中的事务提交后运行代码

本文发布于:2023-10-24 09:53:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523630.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事务   代码   提交后   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!