Creating an appointment reminder app with Python SDK
Creating the application
Now we'll move on to the application itself.
Theappointment_server.py
file controls your app's business logic, allowing it to receive form data and send the appointment reminder by SMS. The full code sample is displayed on the right panel. Copy it and paste the contents into the appointment_server.py
file in your project directory.To get a good feel for how the code works, we'll walk through your application file one function at a time.
First lines of code
Theappointment_server.py
file begins with the following code:from dotenv import load_dotenv
import os
from datetime import datetime, timedelta, timezone
from sinch import SinchClient
from flask import Flask, request, render_template, flash
load_dotenv()
app = Flask(__name__)
app.secret_key = "my_secret_key"
sinch_client = SinchClient(
key_id=os.getenv("KEY_ID"),
key_secret=os.getenv("KEY_SECRET"),
project_id=os.getenv("PROJECT_ID")
)
sinch_client.configuration.sms_region = os.getenv("SMS_REGION")
This sets up your application by doing a few important things.
- The environment variables are loaded into the application from the
.env
file. - A Flask application is created.
- An SDK client object is initialized using the credentials in the
.env
file. This is something that will play a key role in your application. - Finally, the SMS region (
eu
orus
) is set. You only really need to do this outside the United States as the client is initialized with a default region ofus
.
The remind_patient
function
Now we'll review the remind_patient
function, whose job is to send the SMS:def remind_patient(to, message, reminder_datetime):
send_batch_response = sinch_client.sms.batches.send(
body=message,
to=[to],
from_=os.getenv("FROM_NUMBER"),
delivery_report="none",
send_at=reminder_datetime.strftime("%Y-%m-%dT%H:%M:%S")
)
print(send_batch_response)
SinchClient
instance you just created to call the SDK send method. What makes this method powerful is the send_at
parameter. Because the Sinch SMS SDK has message scheduling built in, it's a one-stop shop for any application that requires sending SMS messages at particular times. This removes any need for your application to have auxillary task scheduling infrastucture. Moreover, it means you don't need your app to be running all the time!In addition to
send_at
, the send method has a number of other parameters, including message expiry and delivery reports. These are described in more detail in the REST API reference.The appointment
function
Third let's review the appointment function:
def appointment():
if request.method == "POST":
appointment_date = datetime.strptime(
request.form['appointment_date'],
'%Y-%m-%d'
)
appointment_time = datetime.strptime(
request.form['appointment_time'],
'%H:%M').time()
appointment_datetime = datetime.combine(
appointment_date,
appointment_time
)
now = datetime.now()
if appointment_datetime - timedelta(hours=2, minutes=5) < now:
flash('Appointment must be at least 2:05 hours from now')
return render_template('patient_details.html')
reminder_datetime = appointment_datetime - timedelta(
hours=2,
minutes=5)
message = ("Hi {patient}, you have a Sinch Hospital appointment with"
" Dr {doctor} scheduled for {appointment_time}".format(
patient=request.form['patient'],
doctor=request.form['doctor'],
appointment_time=str(appointment_datetime)
))
country_code = os.getenv('COUNTRY_CODE_US')
if os.getenv('SMS_REGION') == "eu":
country_code = os.getenv('COUNTRY_CODE_EU')
to = country_code + request.form['phone']
reminder_datetime = reminder_datetime.astimezone(timezone.utc)
remind_patient(to, message, reminder_datetime)
return render_template(
'success.html',
patient=request.form['patient'],
doctor=request.form['doctor'],
phone=request.form['phone'],
appointment_datetime=str(appointment_datetime)
)
return render_template('patient_details.html')
appointment
receives form data from the front end and sends an SMS message by calling remind_patient
. Once a message is sent, the user is redirected to the success.html
page.The function also contains validation to make sure any input appointment is scheduled at least two hours and five minutes into the future. This also stops users from accidently setting an appointment for a time in the past.
The Sinch SDK requires phone numbers to have a country code, soappointment
checks the SMS region and adds a US/EU country code to the phone number.Running the application
Finally, this is the code that runs your application:
if __name__ == '__main__':
app.run(port=5010, debug=True)
Congratulations! That's the core of your application completed.