Ahoy! We now recommend you build your appointment reminders with Twilio's built-in Message Scheduling functionality. Head on over to the Message Scheduling documentation to learn more about scheduling messages.
Ready to implement SMS appointment reminders in your Django web application? We'll use the Twilio Python Helper Library and Twilio SMS API to push out reminders to our customers when appointments are near. Here's how it works at a high level:
Check out how Yelp uses SMS to confirm restaurant reservations for diners.
Here are the technologies we'll use:
To implement appointment reminders, we will be working through a series of user stories that describe how to fully implement appointment reminders in a web application.
We'll walk through the code required to satisfy each story, and explore what we needed to add at each step.
All this can be done with the help of Twilio in under half an hour.
We're building this app for Django 2.1 on Python 3.7. We're big fans of Two Scoops of Django and we will use many best practices outlined there.
In addition to Dramatiq, we will use a few other Python libraries to make our task easier:
We will also use PostgreSQL for our database and Redis as our Dramatiq message broker.
1appdirs==1.4.32appnope==0.1.03arrow==0.15.74asgiref==3.2.55attrs==19.3.06backcall==0.1.07black==19.10b08certifi==2019.11.289cfgv==3.1.010chardet==3.0.411click==7.1.112decorator==4.4.213distlib==0.3.014Django==3.0.415django-dramatiq==0.9.116django-bootstrap3==14.0.017django-environ==0.4.518django-forms-bootstrap==3.1.019django-timezone-field==4.020dramatiq[rabbitmq,watch]==1.9.021entrypoints==0.322filelock==3.0.1223flake8==3.7.924identify==1.4.1125idna==2.926importlib-metadata==1.5.027ipdb==0.13.228ipython==7.13.029ipython-genutils==0.2.030isort==4.3.2131jedi==0.16.032mccabe==0.6.133mock==4.0.234model-mommy==2.0.035nodeenv==1.3.536parso==0.6.237pathspec==0.7.038pexpect==4.8.039pickleshare==0.7.540pre-commit==2.2.041prompt-toolkit==3.0.442ptyprocess==0.6.043pycodestyle==2.5.044pyflakes==2.1.145Pygments==2.6.146PyJWT==1.7.147pytz==2019.348PyYAML==5.349redis==3.5.350regex==2020.2.2051requests==2.23.052selenium==3.141.053six==1.14.054sqlparse==0.3.155toml==0.10.056traitlets==4.3.357twilio==6.36.058typed-ast==1.4.159urllib3==1.25.860virtualenv==20.0.1061wcwidth==0.1.862whitenoise==5.1.063zipp==3.1.0
Now that we have all our depenencies defined, we can get started with our first user story: creating a new appointment.
As a user, I want to create an appointment with a name, guest phone number, and a time in the future.
To build an automated appointment reminder app, we probably should start with an appointment. This story requires that we create a model object and a bit of the user interface to create and save a new Appointment
in our system.
At a high level, here's what we will need to add:
Appointment
model to store information we need to send the reminderPOST
data from itAlright, so we know what we need to create a new appointment. Now let's start by looking at the model, where we decide what information we want to store with the appointment.
We only need to store four pieces of data about each appointment to send a reminder:
We also included two additional fields: task_id
and created
. The task_id
field will help us keep track of the corresponding reminder task for this appointment. The created
field is just a timestamp populated when an appointment is created.
Finally, we defined a __str__
method to tell Django how to represent instances of our model as text. This method uses the primary key and the customer's name to create a readable representation of an appointment.
reminders/models.py
1from __future__ import unicode_literals23import redis45from django.core.exceptions import ValidationError6from django.conf import settings7from django.db import models8from django.urls import reverse9from six import python_2_unicode_compatible10from timezone_field import TimeZoneField1112import arrow131415@python_2_unicode_compatible16class Appointment(models.Model):17name = models.CharField(max_length=150)18phone_number = models.CharField(max_length=15)19time = models.DateTimeField()20time_zone = TimeZoneField(default='UTC')2122# Additional fields not visible to users23task_id = models.CharField(max_length=50, blank=True, editable=False)24created = models.DateTimeField(auto_now_add=True)2526def __str__(self):27return 'Appointment #{0} - {1}'.format(self.pk, self.name)2829def get_absolute_url(self):30return reverse('reminders:view_appointment', args=[str(self.id)])3132def clean(self):33"""Checks that appointments are not scheduled in the past"""3435appointment_time = arrow.get(self.time, self.time_zone.zone)3637if appointment_time < arrow.utcnow():38raise ValidationError(39'You cannot schedule an appointment for the past. '40'Please check your time and time_zone')4142def schedule_reminder(self):43"""Schedule a Dramatiq task to send a reminder for this appointment"""4445# Calculate the correct time to send this reminder46appointment_time = arrow.get(self.time, self.time_zone.zone)47reminder_time = appointment_time.shift(minutes=-30)48now = arrow.now(self.time_zone.zone)49milli_to_wait = int(50(reminder_time - now).total_seconds()) * 10005152# Schedule the Dramatiq task53from .tasks import send_sms_reminder54result = send_sms_reminder.send_with_options(55args=(self.pk,),56delay=milli_to_wait)5758return result.options['redis_message_id']5960def save(self, *args, **kwargs):61"""Custom save method which also schedules a reminder"""6263# Check if we have scheduled a reminder for this appointment before64if self.task_id:65# Revoke that task in case its time has changed66self.cancel_task()6768# Save our appointment, which populates self.pk,69# which is used in schedule_reminder70super(Appointment, self).save(*args, **kwargs)7172# Schedule a new reminder task for this appointment73self.task_id = self.schedule_reminder()7475# Save our appointment again, with the new task_id76super(Appointment, self).save(*args, **kwargs)7778def cancel_task(self):79redis_client = redis.Redis(host=settings.REDIS_LOCAL, port=6379, db=0)80redis_client.hdel("dramatiq:default.DQ.msgs", self.task_id)
Our appointment model is now setup, the next step is writting a view for it.
Django lets developers write views as functions or classes.
Class-based views are great when your views need to support CRUD-like features - perfect for our appointments project.
To make a view for creating new Appointment
objects, we'll use Django's generic CreateView class.
All we need to specify is the model it should use and what fields it should include. We don't even need to declare a form - Django will use a ModelForm for us behind the scenes.
Success messages
Our view is ready to go with just those first three lines of code, but we'll make it a little better by adding the SuccessMessageMixin.
This mixin tells our view to pass the success_message
property of our class to the Django messages framework after a successful creation. We will display those messages to the user in our templates.
reminders/views.py
1from django.contrib.messages.views import SuccessMessageMixin2from django.urls import reverse_lazy3from django.views.generic import DetailView4from django.views.generic.edit import CreateView5from django.views.generic.edit import DeleteView6from django.views.generic.edit import UpdateView7from django.views.generic.list import ListView89from .models import Appointment101112class AppointmentListView(ListView):13"""Shows users a list of appointments"""1415model = Appointment161718class AppointmentDetailView(DetailView):19"""Shows users a single appointment"""2021model = Appointment222324class AppointmentCreateView(SuccessMessageMixin, CreateView):25"""Powers a form to create a new appointment"""2627model = Appointment28fields = ['name', 'phone_number', 'time', 'time_zone']29success_message = 'Appointment successfully created.'303132class AppointmentUpdateView(SuccessMessageMixin, UpdateView):33"""Powers a form to edit existing appointments"""3435model = Appointment36fields = ['name', 'phone_number', 'time', 'time_zone']37success_message = 'Appointment successfully updated.'383940class AppointmentDeleteView(DeleteView):41"""Prompts users to confirm deletion of an appointment"""4243model = Appointment44success_url = reverse_lazy('list_appointments')
Now that we have a view to create new appointments, we need to add a new URL to our URL dispatcher so users can get to it.
To satisfy the appointment creation user story, we'll create a new URL at /new
and point it to our AppointmentCreateView
.
Because we're using a class-based view, we pass our view to our URL with the .as_view()
method instead of just using the view's name.
reminders/urls.py
1from django.conf.urls import re_path23from .views import (4AppointmentCreateView,5AppointmentDeleteView,6AppointmentDetailView,7AppointmentListView,8AppointmentUpdateView,9)1011urlpatterns = [12# List and detail views13re_path(r'^$', AppointmentListView.as_view(), name='list_appointments'),14re_path(r'^(?P<pk>[0-9]+)$',15AppointmentDetailView.as_view(),16name='view_appointment'),1718# Create, update, delete19re_path(r'^new$', AppointmentCreateView.as_view(), name='new_appointment'),20re_path(r'^(?P<pk>[0-9]+)/edit$',21AppointmentUpdateView.as_view(),22name='edit_appointment'),23re_path(r'^(?P<pk>[0-9]+)/delete$',24AppointmentDeleteView.as_view(),25name='delete_appointment'),26]
With a view and a model in place, the last big piece we need to let our users create new appointments is the HTML form.
Our form template inherits from our base template, which you can check out at templates/base.html
.
We're using Bootstrap for the front end of our app, and we use the django-forms-bootstrap library to help us render our form with the |as_bootstrap_horizontal
template filter.
By naming this file appointment_form.html
, our AppointmentCreateView
will automatically use this template when rendering its response. If you want to name your template something else, you can specify its name by adding a template_name
property on our view class.
templates/reminders/appointment_form.html
1{% extends "base.html" %}23{% load bootstrap_tags %}45{% block title %}New reminder{% endblock title %}67{% block content %}8<div class="row">9<div class="col-lg-9">10<div class="page-header">11<h1>12{% if not object.pk %}13New appointment14{% else %}15Edit appointment16{% endif %}17</h1>18</div>1920<form class="form-horizontal" method="post">21{% csrf_token %}22{{ form|as_bootstrap_horizontal }}23<div class="form-group">24<div class="col-sm-offset-2 col-sm-10">25<a href="#back" class="btn btn-default">Cancel</a>26<button type="submit" class="btn btn-primary">27{% if not object.pk %}28Create appointment29{% else %}30Update appointment31{% endif %}32</button>33</div>34</div>35</form>36</div>37</div>38{% endblock %}3940{% block page_css %}41<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css" />42{% endblock %}4344{% block page_js %}45<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>46<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>4748<script type="text/javascript">49$(function() {50$('#id_time').datetimepicker({51format: 'MM/DD/YYYY HH:mm',52extraFormats: ['YYYY-MM-DD HH:mm:ss'],53sideBySide: true54});55});56</script>57{% endblock %}
We are not leaving this form yet. Instead, let's take a closer look at one of its widgets: the datepicker.
To make it easier for our users to enter the date and time of an appointment, we'll use a JavaScript datepicker widget.
In this case, bootstrap-datetimepicker is a good fit. We include the necessary CSS and JS files from content delivery networks and then add a little custom JavaScript to initialize the widget on the form input for our time field.
templates/reminders/appointment_form.html
1{% extends "base.html" %}23{% load bootstrap_tags %}45{% block title %}New reminder{% endblock title %}67{% block content %}8<div class="row">9<div class="col-lg-9">10<div class="page-header">11<h1>12{% if not object.pk %}13New appointment14{% else %}15Edit appointment16{% endif %}17</h1>18</div>1920<form class="form-horizontal" method="post">21{% csrf_token %}22{{ form|as_bootstrap_horizontal }}23<div class="form-group">24<div class="col-sm-offset-2 col-sm-10">25<a href="#back" class="btn btn-default">Cancel</a>26<button type="submit" class="btn btn-primary">27{% if not object.pk %}28Create appointment29{% else %}30Update appointment31{% endif %}32</button>33</div>34</div>35</form>36</div>37</div>38{% endblock %}3940{% block page_css %}41<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css" />42{% endblock %}4344{% block page_js %}45<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>46<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>4748<script type="text/javascript">49$(function() {50$('#id_time').datetimepicker({51format: 'MM/DD/YYYY HH:mm',52extraFormats: ['YYYY-MM-DD HH:mm:ss'],53sideBySide: true54});55});56</script>57{% endblock %}
Now let's go back to our Appointment
model to see what happens after we successfully post this form.
When a user clicks "Submit" on our new appointment form, their input will be received by our AppointmentCreateView
and then validated against the fields we specified in our Appointment
model.
If everything looks good, Django will save the new appointment to the database. We need to tell our AppointmentCreateView
where to send our user next.
We could specify a success_url
property on our AppointmentCreateView
, but by default Django's CreateView class will use the newly created object's get_absolute_url
method to figure out where to go next.
So we'll define a get_absolute_url
method on our Appointment
model, which uses Django's reverse utility function to build a URL for this appointment's detail page. You can see that template at templates/reminders/appointment_detail.html
.
And now our users are all set to create new appointments.
reminders/models.py
1from __future__ import unicode_literals23import redis45from django.core.exceptions import ValidationError6from django.conf import settings7from django.db import models8from django.urls import reverse9from six import python_2_unicode_compatible10from timezone_field import TimeZoneField1112import arrow131415@python_2_unicode_compatible16class Appointment(models.Model):17name = models.CharField(max_length=150)18phone_number = models.CharField(max_length=15)19time = models.DateTimeField()20time_zone = TimeZoneField(default='UTC')2122# Additional fields not visible to users23task_id = models.CharField(max_length=50, blank=True, editable=False)24created = models.DateTimeField(auto_now_add=True)2526def __str__(self):27return 'Appointment #{0} - {1}'.format(self.pk, self.name)2829def get_absolute_url(self):30return reverse('reminders:view_appointment', args=[str(self.id)])3132def clean(self):33"""Checks that appointments are not scheduled in the past"""3435appointment_time = arrow.get(self.time, self.time_zone.zone)3637if appointment_time < arrow.utcnow():38raise ValidationError(39'You cannot schedule an appointment for the past. '40'Please check your time and time_zone')4142def schedule_reminder(self):43"""Schedule a Dramatiq task to send a reminder for this appointment"""4445# Calculate the correct time to send this reminder46appointment_time = arrow.get(self.time, self.time_zone.zone)47reminder_time = appointment_time.shift(minutes=-30)48now = arrow.now(self.time_zone.zone)49milli_to_wait = int(50(reminder_time - now).total_seconds()) * 10005152# Schedule the Dramatiq task53from .tasks import send_sms_reminder54result = send_sms_reminder.send_with_options(55args=(self.pk,),56delay=milli_to_wait)5758return result.options['redis_message_id']5960def save(self, *args, **kwargs):61"""Custom save method which also schedules a reminder"""6263# Check if we have scheduled a reminder for this appointment before64if self.task_id:65# Revoke that task in case its time has changed66self.cancel_task()6768# Save our appointment, which populates self.pk,69# which is used in schedule_reminder70super(Appointment, self).save(*args, **kwargs)7172# Schedule a new reminder task for this appointment73self.task_id = self.schedule_reminder()7475# Save our appointment again, with the new task_id76super(Appointment, self).save(*args, **kwargs)7778def cancel_task(self):79redis_client = redis.Redis(host=settings.REDIS_LOCAL, port=6379, db=0)80redis_client.hdel("dramatiq:default.DQ.msgs", self.task_id)
We are now able to create new appointments. Nex, let's quickly implement a few other basic features: listing, updating, and deleting appointments.
As a user, I want to view a list of all future appointments, and be able to edit and delete those appointments.
If you're an organization that handles a lot of appointments, you probably want to be able to view and manage them in a single interface. That's what we'll tackle in this user story. We'll create a UI to:
Because these are basic CRUD-like operations, we'll keep using Django's generic class-based views to save us a lot of work.
reminders/views.py
1from django.contrib.messages.views import SuccessMessageMixin2from django.urls import reverse_lazy3from django.views.generic import DetailView4from django.views.generic.edit import CreateView5from django.views.generic.edit import DeleteView6from django.views.generic.edit import UpdateView7from django.views.generic.list import ListView89from .models import Appointment101112class AppointmentListView(ListView):13"""Shows users a list of appointments"""1415model = Appointment161718class AppointmentDetailView(DetailView):19"""Shows users a single appointment"""2021model = Appointment222324class AppointmentCreateView(SuccessMessageMixin, CreateView):25"""Powers a form to create a new appointment"""2627model = Appointment28fields = ['name', 'phone_number', 'time', 'time_zone']29success_message = 'Appointment successfully created.'303132class AppointmentUpdateView(SuccessMessageMixin, UpdateView):33"""Powers a form to edit existing appointments"""3435model = Appointment36fields = ['name', 'phone_number', 'time', 'time_zone']37success_message = 'Appointment successfully updated.'383940class AppointmentDeleteView(DeleteView):41"""Prompts users to confirm deletion of an appointment"""4243model = Appointment44success_url = reverse_lazy('list_appointments')
We have the high level view of the task, so let's start with listing all the upcoming appointments.
Django's ListView class was born for this.
All we need to do it's to point it at our Appointment
model and it will handle building a QuerySet of all appointments for us.
1from .views import AppointmentListView23re_path(r'^$', AppointmentListView.as_view(), name='list_appointments'),
reminders/views.py
1from django.contrib.messages.views import SuccessMessageMixin2from django.urls import reverse_lazy3from django.views.generic import DetailView4from django.views.generic.edit import CreateView5from django.views.generic.edit import DeleteView6from django.views.generic.edit import UpdateView7from django.views.generic.list import ListView89from .models import Appointment101112class AppointmentListView(ListView):13"""Shows users a list of appointments"""1415model = Appointment161718class AppointmentDetailView(DetailView):19"""Shows users a single appointment"""2021model = Appointment222324class AppointmentCreateView(SuccessMessageMixin, CreateView):25"""Powers a form to create a new appointment"""2627model = Appointment28fields = ['name', 'phone_number', 'time', 'time_zone']29success_message = 'Appointment successfully created.'303132class AppointmentUpdateView(SuccessMessageMixin, UpdateView):33"""Powers a form to edit existing appointments"""3435model = Appointment36fields = ['name', 'phone_number', 'time', 'time_zone']37success_message = 'Appointment successfully updated.'383940class AppointmentDeleteView(DeleteView):41"""Prompts users to confirm deletion of an appointment"""4243model = Appointment44success_url = reverse_lazy('list_appointments')
Our view is ready, now let's check out the template to display this list of appointments.
Our AppointmentListView
passes its list of appointment objects to our template in the object_list
variable.
If that variable is empty, we include a <p>
tag saying there are no upcoming appointments.
Otherwise we populate a table with a row for each appointment in our list. We can use our handy get_absolute_url
method again to include a link to each appointment's detail page.
We also use the {% url %} template tag to include links to our edit and delete views.
templates/reminders/appointment_list.html
1{% extends "base.html" %}23{% block title %}Upcoming reminders{% endblock title %}45{% block content %}6<div class="row">7<div class="col-lg-9">89<div class="page-header">10<h1>Appointments</h1>11</div>1213{% if not object_list %}14<p><strong>No upcoming appointments.</strong> Why not <a href="{% url 'new_appointment' %}">schedule one?</a>15{% endif %}1617<table class="table table-striped">18<thead>19<tr>20<th>Id</th>21<th>Name</th>22<th>Phone number</th>23<th>Time</th>24<th>Created at</th>25<th>Actions</th>26</tr>27</thead>28<tbody>29{% for appointment in object_list %}30<tr>31<td><a href="{{ appointment.get_absolute_url }}">{{ appointment.pk }}</a></td>32<td>{{ appointment.name }}</td>33<td>{{ appointment.phone_number }}</td>34<td>{{ appointment.time }}</td>35<td>{{ appointment.created }}</td>36<td>37<a class="btn btn-default btn-xs" href="{% url 'edit_appointment' appointment.pk %}">Edit</a>38<a class="btn btn-xs btn-danger" href="{% url 'delete_appointment' appointment.pk %}">Delete</a>39</td>40</tr>41{% endfor %}42</tbody>43</table>4445<a class="btn btn-primary" href="{% url 'new_appointment' %}">New</a>46</div>47</div>48{% endblock %}
And now that our appointment listing requirement is complete, let's see how we can use the new Appointment form to update existing appointments.
Django's UpdateView allows you to add a view for updating appointments. Our form template needs a few tweaks, though, to handle prepopulated data from an existing appointment.
Django will store our datetimes precisely, down to the second, but we don't want to bother our users by forcing them to pick the precise second an appointment starts.
To fix this problem we use the extraFormats configuration option of bootstrap-datetimepicker.
By configuring our datetimepicker with a format
value that doesn't ask users for seconds, and an extraFormat
value that does accept datetimes with seconds, our form will populate correctly when Django provides a full datetime to our template.
templates/reminders/appointment_form.html
1{% extends "base.html" %}23{% load bootstrap_tags %}45{% block title %}New reminder{% endblock title %}67{% block content %}8<div class="row">9<div class="col-lg-9">10<div class="page-header">11<h1>12{% if not object.pk %}13New appointment14{% else %}15Edit appointment16{% endif %}17</h1>18</div>1920<form class="form-horizontal" method="post">21{% csrf_token %}22{{ form|as_bootstrap_horizontal }}23<div class="form-group">24<div class="col-sm-offset-2 col-sm-10">25<a href="#back" class="btn btn-default">Cancel</a>26<button type="submit" class="btn btn-primary">27{% if not object.pk %}28Create appointment29{% else %}30Update appointment31{% endif %}32</button>33</div>34</div>35</form>36</div>37</div>38{% endblock %}3940{% block page_css %}41<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css" />42{% endblock %}4344{% block page_js %}45<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>46<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>4748<script type="text/javascript">49$(function() {50$('#id_time').datetimepicker({51format: 'MM/DD/YYYY HH:mm',52extraFormats: ['YYYY-MM-DD HH:mm:ss'],53sideBySide: true54});55});56</script>57{% endblock %}
We now have everything to List
, Create
and Update
an Appointment
. All that is left is handle the Delete
.
DeleteView is an especially handy view class. It shows users a confirmation page before deleting the specified object.
Like UpdateView, DeleteView finds the object to delete by using the pk
parameter in its URL, declared in reminders/urls.py
:
1from .views import AppointmentDeleteView23re_path(r'^/(?P[0-9]+)/delete$', AppointmentDeleteView.as_view(), name='delete_appointment'),
We also need to specify a success_url
property on our view class. This property tells Django where to send users after a successful deletion. In our case, we'll send them back to the list of appointments at the URL named list_appointments
.
When a Django project starts running, it evaluates views before URLs, so we need to use the reverse_lazy utility function to get our appointment list URL instead of reverse
.
By default, our AppointmentDeleteView
will look for a template named appointment_confirm_delete.html
. You can check out ours in the templates/reminders
directory.
And that closes out this user story.
reminders/views.py
1from django.contrib.messages.views import SuccessMessageMixin2from django.urls import reverse_lazy3from django.views.generic import DetailView4from django.views.generic.edit import CreateView5from django.views.generic.edit import DeleteView6from django.views.generic.edit import UpdateView7from django.views.generic.list import ListView89from .models import Appointment101112class AppointmentListView(ListView):13"""Shows users a list of appointments"""1415model = Appointment161718class AppointmentDetailView(DetailView):19"""Shows users a single appointment"""2021model = Appointment222324class AppointmentCreateView(SuccessMessageMixin, CreateView):25"""Powers a form to create a new appointment"""2627model = Appointment28fields = ['name', 'phone_number', 'time', 'time_zone']29success_message = 'Appointment successfully created.'303132class AppointmentUpdateView(SuccessMessageMixin, UpdateView):33"""Powers a form to edit existing appointments"""3435model = Appointment36fields = ['name', 'phone_number', 'time', 'time_zone']37success_message = 'Appointment successfully updated.'383940class AppointmentDeleteView(DeleteView):41"""Prompts users to confirm deletion of an appointment"""4243model = Appointment44success_url = reverse_lazy('list_appointments')
Our users now have everything they need to manage appointments - all that's left to implement is sending the reminders.
As an appointment system, I want to notify a customer via SMS an arbitrary interval before a future appointment.
To satisfy this user story, we need to make our application work asynchronously - on its own independent of any individual user interaction.
One of the most popular Python library for asynchronous tasks is Dramatiq. To integrate Dramatiq with our application, we need to make a few changes:
Appointment
objectIf you're brand new to Dramatiq, you might want to skim its Introduction to Dramatiq page before proceeding.
reminders/tasks.py
1from __future__ import absolute_import23import arrow4import dramatiq56from django.conf import settings7from twilio.rest import Client89from .models import Appointment101112# Uses credentials from the TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN13# environment variables14client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)151617@dramatiq.actor18def send_sms_reminder(appointment_id):19"""Send a reminder to a phone using Twilio SMS"""20# Get our appointment from the database21try:22appointment = Appointment.objects.get(pk=appointment_id)23except Appointment.DoesNotExist:24# The appointment we were trying to remind someone about25# has been deleted, so we don't need to do anything26return2728appointment_time = arrow.get(appointment.time, appointment.time_zone.zone)29body = 'Hi {0}. You have an appointment coming up at {1}.'.format(30appointment.name,31appointment_time.format('h:mm a')32)3334client.messages.create(35body=body,36to=appointment.phone_number,37from_=settings.TWILIO_NUMBER,38)
Next we will configure Dramatiq to work with our project.
Dramatiq and Django are both big Python projects, but they can work together.
By following the instructions in the Dramatiq docs, we can include our Dramatiq settings in our Django settings modules. We can also write our Dramatiq tasks in tasks.py
modules that live inside our Django apps, which keeps our project layout consistent and organized.
To use Dramatiq, you also need a separate service to be your message broker. We used Redis for this project.
The Dramatiq-specific settings in our common.py
settings module is DRAMATIQ_BROKER
.
If you want to see all the steps to get Django, Dramatiq, Redis, and Postgres working on your machine check out the README for this project on GitHub.
appointments/settings/common.py
1"""2Common Django settings for the appointments project.34See the local, test, and production settings modules for the values used5in each environment.67For more information on this file, see8https://docs.djangoproject.com/en/1.8/topics/settings/910For the full list of settings and their values, see11https://docs.djangoproject.com/en/1.8/ref/settings/12"""1314import os1516BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))1718# SECURITY WARNING: don't run with debug turned on in production!19DEBUG = False2021# SECURITY WARNING: keep the secret key used in production secret!22SECRET_KEY = 'not-so-secret'2324# Twilio API25TWILIO_NUMBER = os.environ.get('TWILIO_NUMBER')26TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID')27TWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN')2829DRAMATIQ_BROKER = {30"BROKER": "dramatiq.brokers.redis.RedisBroker",31"OPTIONS": {32"url": 'redis://localhost:6379/0',33},34"MIDDLEWARE": [35"dramatiq.middleware.Prometheus",36"dramatiq.middleware.AgeLimit",37"dramatiq.middleware.TimeLimit",38"dramatiq.middleware.Callbacks",39"dramatiq.middleware.Retries",40"django_dramatiq.middleware.AdminMiddleware",41"django_dramatiq.middleware.DbConnectionsMiddleware",42]43}4445# Reminder time: how early text messages are sent in advance of appointments46REMINDER_TIME = 30 # minutes4748ALLOWED_HOSTS = []4950# Application definition5152DJANGO_APPS = (53'django_dramatiq',54'django.contrib.admin',55'django.contrib.auth',56'django.contrib.contenttypes',57'django.contrib.sessions',58'django.contrib.messages',59'django.contrib.staticfiles'60)6162THIRD_PARTY_APPS = (63'bootstrap3',64'django_forms_bootstrap',65'timezone_field'66)6768LOCAL_APPS = (69'reminders',70)7172INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS7374MIDDLEWARE = (75'django.contrib.sessions.middleware.SessionMiddleware',76'django.middleware.common.CommonMiddleware',77'django.middleware.csrf.CsrfViewMiddleware',78'django.contrib.auth.middleware.AuthenticationMiddleware',79'django.contrib.messages.middleware.MessageMiddleware',80'django.middleware.clickjacking.XFrameOptionsMiddleware',81'django.middleware.security.SecurityMiddleware',82'whitenoise.middleware.WhiteNoiseMiddleware',83)8485ROOT_URLCONF = 'appointments.urls'8687TEMPLATES = [88{89'BACKEND': 'django.template.backends.django.DjangoTemplates',90'DIRS': ['templates/'],91'APP_DIRS': True,92'OPTIONS': {93'context_processors': [94'django.template.context_processors.debug',95'django.template.context_processors.request',96'django.contrib.auth.context_processors.auth',97'django.contrib.messages.context_processors.messages',98],99},100},101]102103CRISPY_TEMPLATE_PACK = 'bootstrap3'104105WSGI_APPLICATION = 'appointments.wsgi.application'106107108# Database109# https://docs.djangoproject.com/en/1.8/ref/settings/#databases110111DATABASES = {112'default': {113'ENGINE': 'django.db.backends.postgresql_psycopg2',114'NAME': 'appointment_reminders'115}116}117118119# Internationalization120# https://docs.djangoproject.com/en/1.8/topics/i18n/121122LANGUAGE_CODE = 'en-us'123124TIME_ZONE = 'UTC'125126USE_I18N = True127128USE_L10N = True129130USE_TZ = True131132133# Static files (CSS, JavaScript, Images)134# https://docs.djangoproject.com/en/1.8/howto/static-files/135136STATIC_ROOT = BASE_DIR + '/staticfiles'137138STATIC_URL = '/static/'
Now that Dramatiq is working with our project, it's time to write a new task for sending a customer an SMS message about their appointment.
Our task takes an appointment's ID - it's primary key - as its only argument. We could pass the Appointment
object itself as the argument, but this best practice ensures our SMS will use the most up-to-date version of our appointment's data.
It also gives us an opportunity to check if the appointment has been deleted before the reminder was sent, which we do at the top of our function. This way we won't send SMS reminders for appointments that don't exist anymore.
reminders/tasks.py
1from __future__ import absolute_import23import arrow4import dramatiq56from django.conf import settings7from twilio.rest import Client89from .models import Appointment101112# Uses credentials from the TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN13# environment variables14client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)151617@dramatiq.actor18def send_sms_reminder(appointment_id):19"""Send a reminder to a phone using Twilio SMS"""20# Get our appointment from the database21try:22appointment = Appointment.objects.get(pk=appointment_id)23except Appointment.DoesNotExist:24# The appointment we were trying to remind someone about25# has been deleted, so we don't need to do anything26return2728appointment_time = arrow.get(appointment.time, appointment.time_zone.zone)29body = 'Hi {0}. You have an appointment coming up at {1}.'.format(30appointment.name,31appointment_time.format('h:mm a')32)3334client.messages.create(35body=body,36to=appointment.phone_number,37from_=settings.TWILIO_NUMBER,38)
Let's stay in our task a bit longer, because the next step is to compose the text of our SMS message.
We use the handy arrow library to format our appointment's time. After that, we use the twilio-python library to send our message.
We instantiate a Twilio REST client at the top of the module, which looks for TWILIO_ACCOUNT_SID
and TWILIO_AUTH_TOKEN
environment variables to authenticate itself. You can find the correct values for you in your account dashboard.
To send the SMS message itself, you'll call client.messages.create()
, passing arguments for the body of the SMS message, the recipient's phone number, and the Twilio phone number you want to send this message from. Twilio will deliver the SMS message immediately.
reminders/tasks.py
1from __future__ import absolute_import23import arrow4import dramatiq56from django.conf import settings7from twilio.rest import Client89from .models import Appointment101112# Uses credentials from the TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN13# environment variables14client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)151617@dramatiq.actor18def send_sms_reminder(appointment_id):19"""Send a reminder to a phone using Twilio SMS"""20# Get our appointment from the database21try:22appointment = Appointment.objects.get(pk=appointment_id)23except Appointment.DoesNotExist:24# The appointment we were trying to remind someone about25# has been deleted, so we don't need to do anything26return2728appointment_time = arrow.get(appointment.time, appointment.time_zone.zone)29body = 'Hi {0}. You have an appointment coming up at {1}.'.format(30appointment.name,31appointment_time.format('h:mm a')32)3334client.messages.create(35body=body,36to=appointment.phone_number,37from_=settings.TWILIO_NUMBER,38)
With our send_sms_reminder
task complete, let's look at how to call it when our appointments are created or updated.
We added a new method on our Appointment
model to help schedule a reminder for an individual appointment.
Our method starts by using arrow again to build a new datetime with the appointment's time
and time_zone
.
Moving backward in time can be tricky in normal Python, but arrow's .replace()
method lets us subtract minutes from our appointment_time
. The REMINDER_TIME
setting defaults to 30 minutes.
We finish by invoking our Dramatiq task, using the delay parameter to tell Dramatiq when this task should execute.
We can't import the send_sms_reminder
task at the top of our models.py
module because the tasks.py
module imports the Appointment
model. Importing it in our schedule_reminder
method avoids a circular dependency.
reminders/models.py
1from __future__ import unicode_literals23import redis45from django.core.exceptions import ValidationError6from django.conf import settings7from django.db import models8from django.urls import reverse9from six import python_2_unicode_compatible10from timezone_field import TimeZoneField1112import arrow131415@python_2_unicode_compatible16class Appointment(models.Model):17name = models.CharField(max_length=150)18phone_number = models.CharField(max_length=15)19time = models.DateTimeField()20time_zone = TimeZoneField(default='UTC')2122# Additional fields not visible to users23task_id = models.CharField(max_length=50, blank=True, editable=False)24created = models.DateTimeField(auto_now_add=True)2526def __str__(self):27return 'Appointment #{0} - {1}'.format(self.pk, self.name)2829def get_absolute_url(self):30return reverse('reminders:view_appointment', args=[str(self.id)])3132def clean(self):33"""Checks that appointments are not scheduled in the past"""3435appointment_time = arrow.get(self.time, self.time_zone.zone)3637if appointment_time < arrow.utcnow():38raise ValidationError(39'You cannot schedule an appointment for the past. '40'Please check your time and time_zone')4142def schedule_reminder(self):43"""Schedule a Dramatiq task to send a reminder for this appointment"""4445# Calculate the correct time to send this reminder46appointment_time = arrow.get(self.time, self.time_zone.zone)47reminder_time = appointment_time.shift(minutes=-30)48now = arrow.now(self.time_zone.zone)49milli_to_wait = int(50(reminder_time - now).total_seconds()) * 10005152# Schedule the Dramatiq task53from .tasks import send_sms_reminder54result = send_sms_reminder.send_with_options(55args=(self.pk,),56delay=milli_to_wait)5758return result.options['redis_message_id']5960def save(self, *args, **kwargs):61"""Custom save method which also schedules a reminder"""6263# Check if we have scheduled a reminder for this appointment before64if self.task_id:65# Revoke that task in case its time has changed66self.cancel_task()6768# Save our appointment, which populates self.pk,69# which is used in schedule_reminder70super(Appointment, self).save(*args, **kwargs)7172# Schedule a new reminder task for this appointment73self.task_id = self.schedule_reminder()7475# Save our appointment again, with the new task_id76super(Appointment, self).save(*args, **kwargs)7778def cancel_task(self):79redis_client = redis.Redis(host=settings.REDIS_LOCAL, port=6379, db=0)80redis_client.hdel("dramatiq:default.DQ.msgs", self.task_id)
The last thing we need to do is ensure Django calls our schedule_reminder
method every time an Appointment
object is created or updated.
The best way to do that is to override our model's save method, including an extra call to schedule_reminder
after the object's primary key has been assigned.
Avoiding duplicate or mistimed reminders
Scheduling a Dramatiq task every time an appointment is saved has an unfortunate side effect - our customers will receive duplicate reminders if an appointment was saved more than once. And those reminders could be sent at the wrong time if an appointment's time
field was changed after its creation.
To fix this, we keep track of each appointment's reminder task through the task_id
field, which stores Dramatiq's unique identifier for each task.
We then look for a previously scheduled task at the top of our custom save
method and cancel it if present.
This guarantees that one and exactly one reminder will be sent for each appointment in our database, and that it will be sent at the most recent time
provided for that appointment.
reminders/models.py
1from __future__ import unicode_literals23import redis45from django.core.exceptions import ValidationError6from django.conf import settings7from django.db import models8from django.urls import reverse9from six import python_2_unicode_compatible10from timezone_field import TimeZoneField1112import arrow131415@python_2_unicode_compatible16class Appointment(models.Model):17name = models.CharField(max_length=150)18phone_number = models.CharField(max_length=15)19time = models.DateTimeField()20time_zone = TimeZoneField(default='UTC')2122# Additional fields not visible to users23task_id = models.CharField(max_length=50, blank=True, editable=False)24created = models.DateTimeField(auto_now_add=True)2526def __str__(self):27return 'Appointment #{0} - {1}'.format(self.pk, self.name)2829def get_absolute_url(self):30return reverse('reminders:view_appointment', args=[str(self.id)])3132def clean(self):33"""Checks that appointments are not scheduled in the past"""3435appointment_time = arrow.get(self.time, self.time_zone.zone)3637if appointment_time < arrow.utcnow():38raise ValidationError(39'You cannot schedule an appointment for the past. '40'Please check your time and time_zone')4142def schedule_reminder(self):43"""Schedule a Dramatiq task to send a reminder for this appointment"""4445# Calculate the correct time to send this reminder46appointment_time = arrow.get(self.time, self.time_zone.zone)47reminder_time = appointment_time.shift(minutes=-30)48now = arrow.now(self.time_zone.zone)49milli_to_wait = int(50(reminder_time - now).total_seconds()) * 10005152# Schedule the Dramatiq task53from .tasks import send_sms_reminder54result = send_sms_reminder.send_with_options(55args=(self.pk,),56delay=milli_to_wait)5758return result.options['redis_message_id']5960def save(self, *args, **kwargs):61"""Custom save method which also schedules a reminder"""6263# Check if we have scheduled a reminder for this appointment before64if self.task_id:65# Revoke that task in case its time has changed66self.cancel_task()6768# Save our appointment, which populates self.pk,69# which is used in schedule_reminder70super(Appointment, self).save(*args, **kwargs)7172# Schedule a new reminder task for this appointment73self.task_id = self.schedule_reminder()7475# Save our appointment again, with the new task_id76super(Appointment, self).save(*args, **kwargs)7778def cancel_task(self):79redis_client = redis.Redis(host=settings.REDIS_LOCAL, port=6379, db=0)80redis_client.hdel("dramatiq:default.DQ.msgs", self.task_id)
Fun tutorial, right? Where can we take it from here?
We used Django's class-based views to help us build out the features to support CRUD operations on our Appointment
model.
We then integrated Dramatiq into our project and used the twilio-python helper library to send SMS reminders about our appointments asynchronously.
You'll find instructions to run this project locally in its GitHub README.
reminders/models.py
1from __future__ import unicode_literals23import redis45from django.core.exceptions import ValidationError6from django.conf import settings7from django.db import models8from django.urls import reverse9from six import python_2_unicode_compatible10from timezone_field import TimeZoneField1112import arrow131415@python_2_unicode_compatible16class Appointment(models.Model):17name = models.CharField(max_length=150)18phone_number = models.CharField(max_length=15)19time = models.DateTimeField()20time_zone = TimeZoneField(default='UTC')2122# Additional fields not visible to users23task_id = models.CharField(max_length=50, blank=True, editable=False)24created = models.DateTimeField(auto_now_add=True)2526def __str__(self):27return 'Appointment #{0} - {1}'.format(self.pk, self.name)2829def get_absolute_url(self):30return reverse('reminders:view_appointment', args=[str(self.id)])3132def clean(self):33"""Checks that appointments are not scheduled in the past"""3435appointment_time = arrow.get(self.time, self.time_zone.zone)3637if appointment_time < arrow.utcnow():38raise ValidationError(39'You cannot schedule an appointment for the past. '40'Please check your time and time_zone')4142def schedule_reminder(self):43"""Schedule a Dramatiq task to send a reminder for this appointment"""4445# Calculate the correct time to send this reminder46appointment_time = arrow.get(self.time, self.time_zone.zone)47reminder_time = appointment_time.shift(minutes=-30)48now = arrow.now(self.time_zone.zone)49milli_to_wait = int(50(reminder_time - now).total_seconds()) * 10005152# Schedule the Dramatiq task53from .tasks import send_sms_reminder54result = send_sms_reminder.send_with_options(55args=(self.pk,),56delay=milli_to_wait)5758return result.options['redis_message_id']5960def save(self, *args, **kwargs):61"""Custom save method which also schedules a reminder"""6263# Check if we have scheduled a reminder for this appointment before64if self.task_id:65# Revoke that task in case its time has changed66self.cancel_task()6768# Save our appointment, which populates self.pk,69# which is used in schedule_reminder70super(Appointment, self).save(*args, **kwargs)7172# Schedule a new reminder task for this appointment73self.task_id = self.schedule_reminder()7475# Save our appointment again, with the new task_id76super(Appointment, self).save(*args, **kwargs)7778def cancel_task(self):79redis_client = redis.Redis(host=settings.REDIS_LOCAL, port=6379, db=0)80redis_client.hdel("dramatiq:default.DQ.msgs", self.task_id)
And with a little code and a dash of configuration, we're ready to get automated appointment reminders firing in our application. Good work!
If you are a Python developer working with Twilio, you might want to check out the following resources for Python: