Creating a reminder app
Let's get into some real-world examples in Celery. Suppose another page on our site now requires a reminder feature. Users can create reminders that will send an e-mail to a specified location at the time specified. We will need a model, a task, and a way to call our task automatically every time a model is created.
Let's start with the following basic SQLAlchemy model:
class Reminder(db.Model): id = db.Column(db.Integer(), primary_key=True) date = db.Column(db.DateTime()) email = db.Column(db.String()) text = db.Column(db.Text()) def __repr__(self): return "<Reminder '{}'>".format(self.text[:20])
Now we need a task that will send an e-mail to the location in the model. In our tasks.py
file, add the following task:
import smtplib from email.mime.text import MIMEText @celery.task( bind=True, ignore_result=True, default_retry_delay=300, max_retries=5 ) def remind(self, pk): reminder = Reminder.query.get(pk) msg...