Skip to contentSkip to navigationSkip to topbar
On this page

Send Appointment Reminders with Python and Flask


(information)

Info

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.

This web application shows how you can use Twilio to send your customers a text message reminding them of upcoming appointments.

We use Flask(link takes you to an external page) to build out the web application that supports our user interface, and Celery(link takes you to an external page) to send the reminder text messages to our customers at the right time.

In this tutorial, we'll point out the key bits of code that make this application work. Check out the project README(link takes you to an external page) on GitHub to see how to run the code yourself.

Check out how Yelp uses SMS to confirm restaurant reservations for diners.(link takes you to an external page)

Let's get started! Click the button below to get started.


Configure the application to use Twilio

configure-the-application-to-use-twilio page anchor

Before we can use the Twilio API to send reminder text messages, we need to configure our account credentials. These can be found on your Twilio Console. You'll also need an SMS-enabled phone number - you can find or purchase a new one to use here.

We put these environment variables in a .env file and use autoenv(link takes you to an external page) to apply them every time we work on the project. More information on how to configure this application can be found in the project README(link takes you to an external page).

Configure the environment variables

configure-the-environment-variables page anchor

.env.example

1
# Environment variables for appointment-reminders-flask
2
3
# App settings
4
export DATABASE_URI=
5
export SECRET_KEY=asupersecr3tkeyshouldgo
6
export CELERY_BROKER_URL=redis://localhost:6379
7
export CELERY_RESULT_BACKEND=redis://localhost:6379
8
9
# Twilio settings
10
export TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXX
11
export TWILIO_AUTH_TOKEN=YYYYYYYYYYYYYYYYYY
12
export TWILIO_NUMBER=+###########

Now that the configuration is taken care of. We'll move on to the application structure.


The application structure

the-application-structure page anchor

The Application object is the heart of any Flask app. Ours initializes the app, sets the URLs, and pulls in all our environment variables.

The celery method is boilerplate to configure Celery using settings and context from our Flask application. Our app uses Redis(link takes you to an external page) as a broker for Celery. But you can also use any of the other available Celery brokers(link takes you to an external page).

To get Celery to run locally on your machine, follow the instructions in the README(link takes you to an external page).

Our core application code

our-core-application-code page anchor

application.py

1
import flask
2
from flask_migrate import Migrate
3
4
from flask_sqlalchemy import SQLAlchemy
5
6
from celery import Celery
7
8
from config import config_classes
9
from views.appointment import (
10
AppointmentFormResource,
11
AppointmentResourceCreate,
12
AppointmentResourceDelete,
13
AppointmentResourceIndex,
14
)
15
16
17
class Route(object):
18
def __init__(self, url, route_name, resource):
19
self.url = url
20
self.route_name = route_name
21
self.resource = resource
22
23
24
handlers = [
25
Route('/', 'appointment.index', AppointmentResourceIndex),
26
Route('/appointment', 'appointment.create', AppointmentResourceCreate),
27
Route(
28
'/appointment/<int:id>/delete', 'appointment.delete', AppointmentResourceDelete
29
),
30
Route('/appointment/new', 'appointment.new', AppointmentFormResource),
31
]
32
33
34
class Application(object):
35
def __init__(self, routes, environment):
36
self.flask_app = flask.Flask(__name__)
37
self.routes = routes
38
self._configure_app(environment)
39
self._set_routes()
40
41
def celery(self):
42
celery = Celery(
43
self.flask_app.import_name, broker=self.flask_app.config['CELERY_BROKER_URL']
44
)
45
celery.conf.update(self.flask_app.config)
46
47
TaskBase = celery.Task
48
49
class ContextTask(TaskBase):
50
abstract = True
51
52
def __call__(self, *args, **kwargs):
53
with self.flask_app.app_context():
54
return TaskBase.__call__(self, *args, **kwargs)
55
56
celery.Task = ContextTask
57
58
return celery
59
60
def _set_routes(self):
61
for route in self.routes:
62
app_view = route.resource.as_view(route.route_name)
63
self.flask_app.add_url_rule(route.url, view_func=app_view)
64
65
def _configure_app(self, env):
66
self.flask_app.config.from_object(config_classes[env])
67
self.db = SQLAlchemy(self.flask_app)
68
self.migrate = Migrate()
69
self.migrate.init_app(self.flask_app, self.db)

With our Application ready, let's create an Appointment model.


The name and phone_number fields tell us who to send the reminder to. The time, timezone, and delta fields tell us when to send the reminder.

We use SQLAlchemy(link takes you to an external page) to power our model and give us a nice ORM interface to use it with.

We added an extra method, get_notification_time, to help us determine the right time to send our reminders. The handy arrow(link takes you to an external page) library helps with this kind of time arithmetic.

models/appointment.py

1
from database import db
2
3
import arrow
4
5
6
class Appointment(db.Model):
7
__tablename__ = 'appointments'
8
9
id = db.Column(db.Integer, primary_key=True)
10
name = db.Column(db.String(50), nullable=False)
11
phone_number = db.Column(db.String(50), nullable=False)
12
delta = db.Column(db.Integer, nullable=False)
13
time = db.Column(db.DateTime, nullable=False)
14
timezone = db.Column(db.String(50), nullable=False)
15
16
def __repr__(self):
17
return '<Appointment %r>' % self.name
18
19
def get_notification_time(self):
20
appointment_time = arrow.get(self.time)
21
reminder_time = appointment_time.shift(minutes=-self.delta)
22
return reminder_time

Next we will use this model to create a new Appointment and schedule a reminder.


Scheduling new reminders

scheduling-new-reminders page anchor

This view handles creating new appointments and scheduling new reminders. It accepts POST data sent to the /appointment URL.

We use WTForms(link takes you to an external page) to validate the form data using a class called NewAppointmentForm that we defined in forms/new_appointment.py.

After that we use arrow(link takes you to an external page) to convert the time zone of the appointment's time to UTC time.

We then save our new Appointment object and schedule the reminder using a Celery task we defined called send_sms_reminder.

views/appointment.py

1
import arrow
2
3
from flask.views import MethodView
4
from flask import render_template, request, redirect, url_for
5
6
from database import db
7
from models.appointment import Appointment
8
from forms.new_appointment import NewAppointmentForm
9
10
11
class AppointmentResourceDelete(MethodView):
12
def post(self, id):
13
appt = db.session.query(Appointment).filter_by(id=id).one()
14
db.session.delete(appt)
15
db.session.commit()
16
17
return redirect(url_for('appointment.index'), code=303)
18
19
20
class AppointmentResourceCreate(MethodView):
21
def post(self):
22
form = NewAppointmentForm(request.form)
23
24
if form.validate():
25
from tasks import send_sms_reminder
26
27
appt = Appointment(
28
name=form.data['name'],
29
phone_number=form.data['phone_number'],
30
delta=form.data['delta'],
31
time=form.data['time'],
32
timezone=form.data['timezone'],
33
)
34
35
appt.time = arrow.get(appt.time, appt.timezone).to('utc').naive
36
37
db.session.add(appt)
38
db.session.commit()
39
send_sms_reminder.apply_async(
40
args=[appt.id], eta=appt.get_notification_time()
41
)
42
43
return redirect(url_for('appointment.index'), code=303)
44
else:
45
return render_template('appointments/new.html', form=form), 400
46
47
48
class AppointmentResourceIndex(MethodView):
49
def get(self):
50
all_appointments = db.session.query(Appointment).all()
51
return render_template('appointments/index.html', appointments=all_appointments)
52
53
54
class AppointmentFormResource(MethodView):
55
def get(self):
56
form = NewAppointmentForm()
57
return render_template('appointments/new.html', form=form)

We'll look at that task next.


Set up a Twilio API client

set-up-a-twilio-api-client page anchor

Our tasks.py module contains the definition for our send_sms_reminder task. At the top of this module we use the twilio-python(link takes you to an external page) library to create a new instance of Client.

We'll use this client object to send a text message using the Twilio API in our send_sms_reminder function.

tasks.py

1
import arrow
2
3
from celery import Celery
4
from sqlalchemy.orm.exc import NoResultFound
5
from twilio.rest import Client
6
7
from reminders import db, app
8
from models.appointment import Appointment
9
10
twilio_account_sid = app.config['TWILIO_ACCOUNT_SID']
11
twilio_auth_token = app.config['TWILIO_AUTH_TOKEN']
12
twilio_number = app.config['TWILIO_NUMBER']
13
client = Client(twilio_account_sid, twilio_auth_token)
14
15
celery = Celery(app.import_name)
16
celery.conf.update(app.config)
17
18
19
class ContextTask(celery.Task):
20
def __call__(self, *args, **kwargs):
21
with app.app_context():
22
return self.run(*args, **kwargs)
23
24
25
celery.Task = ContextTask
26
27
28
@celery.task()
29
def send_sms_reminder(appointment_id):
30
try:
31
appointment = db.session.query(Appointment).filter_by(id=appointment_id).one()
32
except NoResultFound:
33
return
34
35
time = arrow.get(appointment.time).to(appointment.timezone)
36
body = "Hello {0}. You have an appointment at {1}!".format(
37
appointment.name, time.format('h:mm a')
38
)
39
to = appointment.phone_number
40
client.messages.create(to, from_=twilio_number, body=body)

Let's look at send_sms_reminder now.


This is the send_sms_reminder function we called in our appointment.create view. Our function starts with an appointment_id parameter, which we use to retrieve an Appointment object from the database - a Celery best practice.

To compose the body of our text message, we use arrow(link takes you to an external page) again to convert the UTC time stored in our appointment to the local time zone of our customer.

After that, sending the message itself is a call to client.messages.create(). We use our customer's phone number as the to argument and our Twilio number as the from_ argument.

Perform the actual task of sending a SMS

perform-the-actual-task-of-sending-a-sms page anchor

tasks.py

1
import arrow
2
3
from celery import Celery
4
from sqlalchemy.orm.exc import NoResultFound
5
from twilio.rest import Client
6
7
from reminders import db, app
8
from models.appointment import Appointment
9
10
twilio_account_sid = app.config['TWILIO_ACCOUNT_SID']
11
twilio_auth_token = app.config['TWILIO_AUTH_TOKEN']
12
twilio_number = app.config['TWILIO_NUMBER']
13
client = Client(twilio_account_sid, twilio_auth_token)
14
15
celery = Celery(app.import_name)
16
celery.conf.update(app.config)
17
18
19
class ContextTask(celery.Task):
20
def __call__(self, *args, **kwargs):
21
with app.app_context():
22
return self.run(*args, **kwargs)
23
24
25
celery.Task = ContextTask
26
27
28
@celery.task()
29
def send_sms_reminder(appointment_id):
30
try:
31
appointment = db.session.query(Appointment).filter_by(id=appointment_id).one()
32
except NoResultFound:
33
return
34
35
time = arrow.get(appointment.time).to(appointment.timezone)
36
body = "Hello {0}. You have an appointment at {1}!".format(
37
appointment.name, time.format('h:mm a')
38
)
39
to = appointment.phone_number
40
client.messages.create(to, from_=twilio_number, body=body)

That's it! Our Flask application is all set to send out reminders for upcoming appointments.


We hope you found this sample application useful.

If you're a Python developer working with Twilio and Flask, you might enjoy these other tutorials:

Click to Call

Put a button on your web page that connects visitors to live support or sales people via telephone.

Two-Factor Authentication

Improve the security of your Flask app's login functionality by adding two-factor authentication via text message.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.