检查数据库中新警报的 Django 函数

Django function that checking new alerts in DB

我将在我的拼贴画中开始我的第一个 django 项目,我想知道如何制作一个函数来检查每 x 次或当我在 "alerts" table 中有一个新行时数据库并在向用户发送电子邮件或短信后。

我的项目是web系统监控。

尝试使用 cron jobs,使用 cron jobs 可以周期性地每隔一段时间执行一个操作。

要在 django 中创建 cron jobs,您必须创建一个 custom django-admin command

  • 在您的其中一个应用程序中创建一个文件夹 management,然后在 management 文件夹中创建另一个文件夹 commands
  • commands 文件夹中创建一个文件 my_costum_command.py。它是将出现在 manage.py 命令列表中的命令的名称。 (该应用必须在已安装的应用中)
  • 导入检查数据库所需的库和模型

    from django.core.management.base import BaseCommand

  • 然后,创建一个 class 比如:

    class Command(BaseCommand):
        help = 'Description of the command'
        def handle(self, *args, **kwargs):
        # your code for the action (checking database)
        # check the database and send email if needs
    

现在,命令将从manage.py

开始执行

然后,创建一个 cron 作业并每隔一段时间(此处每小时一次)执行命令:

# m h  dom mon dow   command
0 * * * * /home/mysite/venv/bin/python /home/mysite/mysite/manage.py my_custom_command

这里是 docs 如何创建自定义 django-admin 命令