Django/Python:如何监控MySQL数据库并在时间戳=NOW()时触发邮件?
如果我想做一个报警系统,我该怎么实现这些功能呢?
我有一个MySQL数据库,用来存储用户的消息和时间戳(或者说日期时间)。我想在时间戳晚于当前时间戳的时候,给用户发送邮件。
我该如何在基于Django/python的网页应用中实现这个功能呢?我需要使用定时任务来监控数据库吗?还是说有工具可以监控数据库,并触发API调用来发送邮件呢?
谢谢大家!我期待你们的好答案!
1 个回答
1
你可以在Django的视图里直接处理这个问题,其实不需要外部的定时任务去操作你的数据库。为了更清楚一点,你是想在视图里处理完消息后就发送邮件,还是说有其他的动作导致消息被创建,然后你再想发送邮件呢?
发送邮件的代码可能长这样:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
import logging
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
def send_message(to):
log.error('starting send email')
subject, from_email = 'Message Confirmation', 'youraddress@gmail.com'
html_content = render_to_string('emails/message.html', {'email': str(to)})
# this strips the html, so people will have the text as well.
text_content = strip_tags(html_content)
# create the email, and attach the HTML version as well.
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
在你的视图里,你可以立即发送这封邮件,代码可以是:
send_message(user_email)
或者你也可以检查一下消息的日期,如果时间符合某个条件,就发送邮件。