在数据库更新时触发Django模块 [英] Trigger Django module on Database update
问题描述
我想开发一个监视数据库中新记录的应用程序,并允许我在插入新记录时在Django应用程序的上下文中执行一个方法.
I want to develop an application that monitors the database for new records and allows me to execute a method in the context of my Django application when a new record is inserted.
我计划使用Celery任务检查自上次检查以来数据库的更改并触发上述方法的方法.
I am planning to use an approach where a Celery task checks the database for changes since the last check and triggers the above method.
有没有更好的方法来实现这一目标?
Is there a better way to achieve this?
我使用SQLite作为后端并尝试了apsw的setupdatehook API,但它似乎没有在Django上下文中运行我的模块.
I'm using SQLite as the backend and tried apsw's setupdatehook API, but it doesn't seem to run my module in Django context.
注意:更新是由Django之外的其他应用程序进行的.
NOTE: The updates are made by a different application outside Django.
推荐答案
创建一个celery任务,以执行您需要对该对象执行的所有操作:
Create a celery task to do whatever it is you need to do with the object:
tasks.py
from celery.decorators import task
@task()
def foo(object):
object.do_some_calculation()
然后创建一个 django信号,该信号在每次您的模型已保存,在Celery中排队您的任务:
Then create a django signal that is fired every time an instance of your Model is saved , queuing up your task in Celery:
models.py
class MyModel(models.Model):
...
from django.db.models.signals import post_save
from django.dispatch import receiver
from mymodel import tasks
@receiver(post_save, sender=MyModel)
def queue_task(sender, instance, created, **kwargs):
tasks.foo.delay(object=instance)
要注意的重要一点是django的信号是同步的,换句话说, queue_task
函数在请求周期内运行,但是所有 queue_task
函数正在执行的操作是告诉Celery在b背景下处理作品的实际胆量( do_some_calculation
)
What's important to note that is django's signals are synchronous, in other words the queue_task
function runs within the request cycle, but all the queue_task
function is doing is telling Celery to handle the actual guts of the work (do_some_calculation
) in theb background
这篇关于在数据库更新时触发Django模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!