What we need is something to handle HTTP requests. Thankfully Flask does this for us and is extremely easy to use!
First thing we’ll do is import all of the stuff we need/want:
from flask import Flask, request, redirect, make_response from twilio import twiml as TwiML, TwilioRestException from twilio.rest import TwilioRestClient from db import * from peewee import SelectQuery
This imports the important Flask and Twilio options as well as our database reference. Now we need to initialize Flask before we get too happy:
app = Flask(__name__)
In a way you can think of this as like using logging.Logger(), you typically pass it __name__ so that it has a reference.
Now, lets make it so when we go to http://ip_address:5000/ we see a message:
@app.route("/", methods=['GET', 'POST']) def main(): return "You sure?!"
The method name is irrelevant (though has to be unique per route). The “/” is the same as when visiting http://ip_address:5000/, and we will let the main handler support both GET and POST requests. Now, when you visit the URL you’ll receive “You sure?!” in your browser.
After, we need this two-liner:
if __name__ == "__main__": app.run(host='192.168.0.102', debug=True)
However, change the IP in host to one that is reachable from the Internet (or set up port forwarding) so later on Twilio will be able to connect to the web service. Now, open up your browser once you run the script and you should see the message. 😀
This was short but, then again, there’s not a whole lot that needed to be covered to get Flask up and running by itself. Next, however, will be when the fun starts and we work with Twilio’s helper library.