在 Django 中提交事务后运行代码 [英] run code after transaction commit in Django

查看:27
本文介绍了在 Django 中提交事务后运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Django 中提交事务后有没有办法运行一些代码?

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

我需要将一些消息发送到rabbitmq 服务器以进行离线处理,但是在提交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.

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

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).

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

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

推荐答案

django-transaction-hooks 为 Django < 解决了这个问题1.9,功能是内置于Django 1.9+:

django-transaction-hooks solves this problem for Django < 1.9, and the functionality is built into Django 1.9+:

from django.db import transaction

def do_something():
    pass  # send a mail, invalidate a cache, fire off a Celery task, etc.

transaction.on_commit(do_something)

这篇关于在 Django 中提交事务后运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆