开发者

Django/Python: How can i monitor mysql database and trigger email when timestamp = NOW()?

If i want to make an alerting system. How can I implement those feature?

I have a MySQ开发者_运维百科L database storing user's message and timestamp (or datetime). I want to trigger sending email out to that user if timestamp is greater than current timestamp.

How can i implement that feature using Django/python based web application? Do i need to use cron job to monitor database? or is there a tool to monitor database and trigger an API calls to send out email?

Thanks guys! I'll wait for great answers!


You should be able to do this within your view in Django, and really not need to have an external cron run on your database. To clarify a little, are you wanting the email to be sent when the message is processed in the view or does some other action cause messages to be created and then you want the message sent.

For sending the email itself you might have something like:

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

From within your view you could fire this email off immediately with:

send_message(user_email)

Or you could check the date of the message and if the time is a certain value then send.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜