我想开发一个应用程序来监视数据库中的新记录,并允许我在插入新记录时在我的 Django 应用程序的上下文中执行一个方法。
我计划使用一种方法,其中 Celery 任务检查数据库自上次检查以来的更改并触发上述方法。
有没有更好的方法来实现这一目标?
我使用 SQLite 作为后端并尝试了 apsw 的 setupdatehook API,但它似乎没有在 Django 上下文中运行我的模块。
注意:更新是由 Django 之外的不同应用程序进行的。
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()
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)
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
A better way would be to have that application that modifies the records call yours. Or at least make a celery queue entry so that you don't really have to query the database too often to see if something changed.
But if that is not an option, letting celery query the database to find if something changed is probably the next best option. (surely better than the other possible option of calling a web service from the database as a trigger, which you should really avoid.)