A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.twilio.com/docs/tutorials/walkthrough/masked-numbers/python/flask below:

Masked Phone Numbers with Python and Flask

Masked Phone Numbers with Python and Flask

This Flask (link takes you to an external page) sample application models an amazing rental experience that a vacation rental company might provide, but with more Klingons (link takes you to an external page) .

Host users can offer rental properties which other guest users can reserve. The guest and the host can then anonymously communicate via a disposable Twilio phone number created just for a reservation. In this tutorial, we'll show you the key bits of code to make this work.

To run this sample app yourself, download the code and follow the instructions on GitHub (link takes you to an external page) .

(warning)

Legal implications of managing communications between users

If you choose to manage communications between your users, including voice calls, text-based messages (e.g., SMS), and chat, you may need to comply with certain laws and regulations, including those regarding obtaining consent. Additional information regarding legal compliance considerations and best practices for using Twilio to manage and record communications between your users, such as when using Twilio Proxy, can be found here (link takes you to an external page) .

Notice: Twilio recommends that you consult with your legal counsel to make sure that you are complying with all applicable laws in connection with communications you record or store using Twilio.

Read how Lyft uses masked phone numbers to let customers securely contact drivers. (link takes you to an external page)

The first step in connecting a guest and a host is creating a reservation.

We handle here a submission form for a new reservation. After we save the reservation to the database, we send the host an SMS message asking them to accept or reject the reservation.

1

from twilio.twiml.messaging_response import MessagingResponse

2

from twilio.twiml.voice_response import VoiceResponse

4

from airtng_flask import db, bcrypt, app, login_manager

5

from flask import g, request

6

from flask.ext.login import login_user, logout_user, current_user, login_required

8

from airtng_flask.forms import RegisterForm, LoginForm, VacationPropertyForm, ReservationForm, \

9

ReservationConfirmationForm, ExchangeForm

10

from airtng_flask.view_helpers import twiml, view, redirect_to, view_with_params

11

from airtng_flask.models import init_models_module

13

init_models_module(db, bcrypt, app)

15

from airtng_flask.models.user import User

16

from airtng_flask.models.vacation_property import VacationProperty

17

from airtng_flask.models.reservation import Reservation

20

@app.route('/', methods=["GET", "POST"])

21

@app.route('/register', methods=["GET", "POST"])

24

if request.method == 'POST':

25

if form.validate_on_submit():

27

if User.query.filter(User.email == form.email.data).count() > 0:

28

form.email.errors.append("Email address already in use.")

29

return view('register', form)

34

password=form.password.data,

35

phone_number="+{0}{1}".format(form.country_code.data, form.phone_number.data),

36

area_code=str(form.phone_number.data)[0:3])

40

login_user(user, remember=True)

42

return redirect_to('home')

44

return view('register', form)

46

return view('register', form)

49

@app.route('/login', methods=["GET", "POST"])

52

if request.method == 'POST':

53

if form.validate_on_submit():

54

candidate_user = User.query.filter(User.email == form.email.data).first()

56

if candidate_user is None or not bcrypt.check_password_hash(candidate_user.password,

58

form.password.errors.append("Invalid credentials.")

59

return view('login', form)

61

login_user(candidate_user, remember=True)

62

return redirect_to('home')

63

return view('login', form)

66

@app.route('/logout', methods=["POST"])

70

return redirect_to('home')

73

@app.route('/home', methods=["GET"])

79

@app.route('/properties', methods=["GET"])

82

vacation_properties = VacationProperty.query.all()

83

return view_with_params('properties', vacation_properties=vacation_properties)

86

@app.route('/properties/new', methods=["GET", "POST"])

89

form = VacationPropertyForm()

90

if request.method == 'POST':

91

if form.validate_on_submit():

92

host = User.query.get(current_user.get_id())

94

property = VacationProperty(form.description.data, form.image_url.data, host)

97

return redirect_to('properties')

99

return view('property_new', form)

102

@app.route('/reservations/', methods=["POST"], defaults={'property_id': None})

103

@app.route('/reservations/<property_id>', methods=["GET", "POST"])

105

def new_reservation(property_id):

108

form.property_id.data = property_id

110

if request.method == 'POST':

111

if form.validate_on_submit():

112

guest = User.query.get(current_user.get_id())

114

vacation_property = VacationProperty.query.get(form.property_id.data)

115

reservation = Reservation(form.message.data, vacation_property, guest)

116

db.session.add(reservation)

119

reservation.notify_host()

121

return redirect_to('properties')

123

if property_id is not None:

124

vacation_property = VacationProperty.query.get(property_id)

126

return view_with_params('reservation', vacation_property=vacation_property, form=form)

129

@app.route('/reservations', methods=["GET"])

132

user = User.query.get(current_user.get_id())

134

reservations_as_host = Reservation.query \

135

.filter(VacationProperty.host_id == current_user.get_id() and len(VacationProperty.reservations) > 0) \

136

.join(VacationProperty) \

137

.filter(Reservation.vacation_property_id == VacationProperty.id) \

140

reservations_as_guest = user.reservations

142

return view_with_params('reservations',

143

reservations_as_guest=reservations_as_guest,

144

reservations_as_host=reservations_as_host)

147

@app.route('/reservations/confirm', methods=["POST"])

148

def confirm_reservation():

149

form = ReservationConfirmationForm()

150

sms_response_text = "Sorry, it looks like you don't have any reservations to respond to."

152

user = User.query.filter(User.phone_number == form.From.data).first()

153

reservation = Reservation \

155

.filter(Reservation.status == 'pending'

156

and Reservation.vacation_property.host.id == user.id) \

159

if reservation is not None:

161

if 'yes' in form.Body.data or 'accept' in form.Body.data:

163

reservation.buy_number(user.area_code)

169

sms_response_text = "You have successfully {0} the reservation".format(reservation.status)

170

reservation.notify_guest()

172

return twiml(_respond_message(sms_response_text))

175

@app.route('/exchange/sms', methods=["POST"])

179

outgoing_number = _gather_outgoing_phone_number(form.From.data, form.To.data)

181

response = MessagingResponse()

182

response.message(form.Body.data, to=outgoing_number)

186

@app.route('/exchange/voice', methods=["POST"])

189

outgoing_number = _gather_outgoing_phone_number(form.From.data, form.To.data)

191

response = VoiceResponse()

192

response.play("http://howtodocs.s3.amazonaws.com/howdy-tng.mp3")

193

response.dial(outgoing_number)

201

uri_pattern = request.url_rule

202

if current_user.is_authenticated and (

203

uri_pattern == '/' or uri_pattern == '/login' or uri_pattern == '/register'):

207

@login_manager.user_loader

210

return User.query.get(id)

215

def _gather_outgoing_phone_number(incoming_phone_number, anonymous_phone_number):

216

reservation = Reservation.query \

217

.filter(Reservation.anonymous_phone_number == anonymous_phone_number) \

221

raise Exception('Reservation not found for {0}'.format(incoming_phone_number))

223

if reservation.guest.phone_number == incoming_phone_number:

224

return reservation.vacation_property.host.phone_number

226

return reservation.guest.phone_number

229

def _respond_message(message):

230

response = MessagingResponse()

231

response.message(message)

Part of our reservation system is receiving reservation requests from potential renters. However, these reservations need to be confirmed. Let's see how we would handle this step.

Before the reservation is finalized, the host needs to confirm that the property was reserved. Learn how to automate this process on our first AirTNG tutorial Workflow Automation.

1

from twilio.twiml.messaging_response import MessagingResponse

2

from twilio.twiml.voice_response import VoiceResponse

4

from airtng_flask import db, bcrypt, app, login_manager

5

from flask import g, request

6

from flask.ext.login import login_user, logout_user, current_user, login_required

8

from airtng_flask.forms import RegisterForm, LoginForm, VacationPropertyForm, ReservationForm, \

9

ReservationConfirmationForm, ExchangeForm

10

from airtng_flask.view_helpers import twiml, view, redirect_to, view_with_params

11

from airtng_flask.models import init_models_module

13

init_models_module(db, bcrypt, app)

15

from airtng_flask.models.user import User

16

from airtng_flask.models.vacation_property import VacationProperty

17

from airtng_flask.models.reservation import Reservation

20

@app.route('/', methods=["GET", "POST"])

21

@app.route('/register', methods=["GET", "POST"])

24

if request.method == 'POST':

25

if form.validate_on_submit():

27

if User.query.filter(User.email == form.email.data).count() > 0:

28

form.email.errors.append("Email address already in use.")

29

return view('register', form)

34

password=form.password.data,

35

phone_number="+{0}{1}".format(form.country_code.data, form.phone_number.data),

36

area_code=str(form.phone_number.data)[0:3])

40

login_user(user, remember=True)

42

return redirect_to('home')

44

return view('register', form)

46

return view('register', form)

49

@app.route('/login', methods=["GET", "POST"])

52

if request.method == 'POST':

53

if form.validate_on_submit():

54

candidate_user = User.query.filter(User.email == form.email.data).first()

56

if candidate_user is None or not bcrypt.check_password_hash(candidate_user.password,

58

form.password.errors.append("Invalid credentials.")

59

return view('login', form)

61

login_user(candidate_user, remember=True)

62

return redirect_to('home')

63

return view('login', form)

66

@app.route('/logout', methods=["POST"])

70

return redirect_to('home')

73

@app.route('/home', methods=["GET"])

79

@app.route('/properties', methods=["GET"])

82

vacation_properties = VacationProperty.query.all()

83

return view_with_params('properties', vacation_properties=vacation_properties)

86

@app.route('/properties/new', methods=["GET", "POST"])

89

form = VacationPropertyForm()

90

if request.method == 'POST':

91

if form.validate_on_submit():

92

host = User.query.get(current_user.get_id())

94

property = VacationProperty(form.description.data, form.image_url.data, host)

97

return redirect_to('properties')

99

return view('property_new', form)

102

@app.route('/reservations/', methods=["POST"], defaults={'property_id': None})

103

@app.route('/reservations/<property_id>', methods=["GET", "POST"])

105

def new_reservation(property_id):

108

form.property_id.data = property_id

110

if request.method == 'POST':

111

if form.validate_on_submit():

112

guest = User.query.get(current_user.get_id())

114

vacation_property = VacationProperty.query.get(form.property_id.data)

115

reservation = Reservation(form.message.data, vacation_property, guest)

116

db.session.add(reservation)

119

reservation.notify_host()

121

return redirect_to('properties')

123

if property_id is not None:

124

vacation_property = VacationProperty.query.get(property_id)

126

return view_with_params('reservation', vacation_property=vacation_property, form=form)

129

@app.route('/reservations', methods=["GET"])

132

user = User.query.get(current_user.get_id())

134

reservations_as_host = Reservation.query \

135

.filter(VacationProperty.host_id == current_user.get_id() and len(VacationProperty.reservations) > 0) \

136

.join(VacationProperty) \

137

.filter(Reservation.vacation_property_id == VacationProperty.id) \

140

reservations_as_guest = user.reservations

142

return view_with_params('reservations',

143

reservations_as_guest=reservations_as_guest,

144

reservations_as_host=reservations_as_host)

147

@app.route('/reservations/confirm', methods=["POST"])

148

def confirm_reservation():

149

form = ReservationConfirmationForm()

150

sms_response_text = "Sorry, it looks like you don't have any reservations to respond to."

152

user = User.query.filter(User.phone_number == form.From.data).first()

153

reservation = Reservation \

155

.filter(Reservation.status == 'pending'

156

and Reservation.vacation_property.host.id == user.id) \

159

if reservation is not None:

161

if 'yes' in form.Body.data or 'accept' in form.Body.data:

163

reservation.buy_number(user.area_code)

169

sms_response_text = "You have successfully {0} the reservation".format(reservation.status)

170

reservation.notify_guest()

172

return twiml(_respond_message(sms_response_text))

175

@app.route('/exchange/sms', methods=["POST"])

179

outgoing_number = _gather_outgoing_phone_number(form.From.data, form.To.data)

181

response = MessagingResponse()

182

response.message(form.Body.data, to=outgoing_number)

186

@app.route('/exchange/voice', methods=["POST"])

189

outgoing_number = _gather_outgoing_phone_number(form.From.data, form.To.data)

191

response = VoiceResponse()

192

response.play("http://howtodocs.s3.amazonaws.com/howdy-tng.mp3")

193

response.dial(outgoing_number)

201

uri_pattern = request.url_rule

202

if current_user.is_authenticated and (

203

uri_pattern == '/' or uri_pattern == '/login' or uri_pattern == '/register'):

207

@login_manager.user_loader

210

return User.query.get(id)

215

def _gather_outgoing_phone_number(incoming_phone_number, anonymous_phone_number):

216

reservation = Reservation.query \

217

.filter(Reservation.anonymous_phone_number == anonymous_phone_number) \

221

raise Exception('Reservation not found for {0}'.format(incoming_phone_number))

223

if reservation.guest.phone_number == incoming_phone_number:

224

return reservation.vacation_property.host.phone_number

226

return reservation.guest.phone_number

229

def _respond_message(message):

230

response = MessagingResponse()

231

response.message(message)

Once the reservation is confirmed, we need to purchase a Twilio number that the guest and host can use to communicate.

Here we use the Twilio Python helper library to search for and buy a new phone number to associate with the reservation. We start by searching for a number with a local area code - if we can't find one, we take any available phone number in that country.

When we buy the number, we designate a TwiML Application that will handle webhook (link takes you to an external page) requests when the new number receives an incoming call or text.

We then save the new phone number on our Reservation model. Therefore when our app receives calls or messages to this number we know which reservation the call or text belongs to.

airtng_flask/models/reservation.py

1

from airtng_flask.models import app_db, auth_token, account_sid, phone_number, application_sid

2

from flask import render_template

3

from twilio.rest import Client

8

class Reservation(DB.Model):

9

__tablename__ = "reservations"

11

id = DB.Column(DB.Integer, primary_key=True)

12

message = DB.Column(DB.String, nullable=False)

13

status = DB.Column(DB.Enum('pending', 'confirmed', 'rejected', name='reservation_status_enum'),

15

anonymous_phone_number = DB.Column(DB.String, nullable=True)

16

guest_id = DB.Column(DB.Integer, DB.ForeignKey('users.id'))

17

vacation_property_id = DB.Column(DB.Integer, DB.ForeignKey('vacation_properties.id'))

18

guest = DB.relationship("User", back_populates="reservations")

19

vacation_property = DB.relationship("VacationProperty", back_populates="reservations")

21

def __init__(self, message, vacation_property, guest):

24

self.vacation_property = vacation_property

28

self.status = 'confirmed'

34

return '<Reservation {0}>'.format(self.id)

37

self._send_message(self.vacation_property.host.phone_number,

38

render_template('messages/sms_host.txt',

40

description=self.vacation_property.description,

44

self._send_message(self.guest.phone_number,

45

render_template('messages/sms_guest.txt',

46

description=self.vacation_property.description,

49

def buy_number(self, area_code):

50

numbers = self._get_twilio_client().available_phone_numbers("US") \

52

.list(area_code=area_code,

57

number = self._purchase_number(numbers[0])

58

self.anonymous_phone_number = number

61

numbers = self._get_twilio_client().available_phone_numbers("US") \

63

.list(sms_enabled=True, voice_enabled=True)

66

number = self._purchase_number(numbers[0])

67

self.anonymous_phone_number = number

72

def _purchase_number(self, number):

73

return self._get_twilio_client().incoming_phone_numbers \

74

.create(sms_application_sid=application_sid(),

75

voice_application_sid=application_sid(),

79

def _get_twilio_client(self):

80

return Client(account_sid(), auth_token())

82

def _send_message(self, to, message):

83

self._get_twilio_client().messages \

Now that each reservation has a Twilio Phone Number, we can see how the application will look up reservations as guest or host calls come in.

When someone messages or calls one of the Twilio numbers (that we purchased for a reservation) Twilio makes a request to the URL you set in the TwiML app. That request will contain some helpful metadata:

Take a look at Twilio's SMS Documentation and Twilio's Voice Documentation for a full list of the parameters you can use.

In our code we use the To parameter sent by Twilio to find a reservation that has the number we bought stored in it, as this is the number both hosts and guests will call and send SMSs to.

1

from twilio.twiml.messaging_response import MessagingResponse

2

from twilio.twiml.voice_response import VoiceResponse

4

from airtng_flask import db, bcrypt, app, login_manager

5

from flask import g, request

6

from flask.ext.login import login_user, logout_user, current_user, login_required

8

from airtng_flask.forms import RegisterForm, LoginForm, VacationPropertyForm, ReservationForm, \

9

ReservationConfirmationForm, ExchangeForm

10

from airtng_flask.view_helpers import twiml, view, redirect_to, view_with_params

11

from airtng_flask.models import init_models_module

13

init_models_module(db, bcrypt, app)

15

from airtng_flask.models.user import User

16

from airtng_flask.models.vacation_property import VacationProperty

17

from airtng_flask.models.reservation import Reservation

20

@app.route('/', methods=["GET", "POST"])

21

@app.route('/register', methods=["GET", "POST"])

24

if request.method == 'POST':

25

if form.validate_on_submit():

27

if User.query.filter(User.email == form.email.data).count() > 0:

28

form.email.errors.append("Email address already in use.")

29

return view('register', form)

34

password=form.password.data,

35

phone_number="+{0}{1}".format(form.country_code.data, form.phone_number.data),

36

area_code=str(form.phone_number.data)[0:3])

40

login_user(user, remember=True)

42

return redirect_to('home')

44

return view('register', form)

46

return view('register', form)

49

@app.route('/login', methods=["GET", "POST"])

52

if request.method == 'POST':

53

if form.validate_on_submit():

54

candidate_user = User.query.filter(User.email == form.email.data).first()

56

if candidate_user is None or not bcrypt.check_password_hash(candidate_user.password,

58

form.password.errors.append("Invalid credentials.")

59

return view('login', form)

61

login_user(candidate_user, remember=True)

62

return redirect_to('home')

63

return view('login', form)

66

@app.route('/logout', methods=["POST"])

70

return redirect_to('home')

73

@app.route('/home', methods=["GET"])

79

@app.route('/properties', methods=["GET"])

82

vacation_properties = VacationProperty.query.all()

83

return view_with_params('properties', vacation_properties=vacation_properties)

86

@app.route('/properties/new', methods=["GET", "POST"])

89

form = VacationPropertyForm()

90

if request.method == 'POST':

91

if form.validate_on_submit():

92

host = User.query.get(current_user.get_id())

94

property = VacationProperty(form.description.data, form.image_url.data, host)

97

return redirect_to('properties')

99

return view('property_new', form)

102

@app.route('/reservations/', methods=["POST"], defaults={'property_id': None})

103

@app.route('/reservations/<property_id>', methods=["GET", "POST"])

105

def new_reservation(property_id):

108

form.property_id.data = property_id

110

if request.method == 'POST':

111

if form.validate_on_submit():

112

guest = User.query.get(current_user.get_id())

114

vacation_property = VacationProperty.query.get(form.property_id.data)

115

reservation = Reservation(form.message.data, vacation_property, guest)

116

db.session.add(reservation)

119

reservation.notify_host()

121

return redirect_to('properties')

123

if property_id is not None:

124

vacation_property = VacationProperty.query.get(property_id)

126

return view_with_params('reservation', vacation_property=vacation_property, form=form)

129

@app.route('/reservations', methods=["GET"])

132

user = User.query.get(current_user.get_id())

134

reservations_as_host = Reservation.query \

135

.filter(VacationProperty.host_id == current_user.get_id() and len(VacationProperty.reservations) > 0) \

136

.join(VacationProperty) \

137

.filter(Reservation.vacation_property_id == VacationProperty.id) \

140

reservations_as_guest = user.reservations

142

return view_with_params('reservations',

143

reservations_as_guest=reservations_as_guest,

144

reservations_as_host=reservations_as_host)

147

@app.route('/reservations/confirm', methods=["POST"])

148

def confirm_reservation():

149

form = ReservationConfirmationForm()

150

sms_response_text = "Sorry, it looks like you don't have any reservations to respond to."

152

user = User.query.filter(User.phone_number == form.From.data).first()

153

reservation = Reservation \

155

.filter(Reservation.status == 'pending'

156

and Reservation.vacation_property.host.id == user.id) \

159

if reservation is not None:

161

if 'yes' in form.Body.data or 'accept' in form.Body.data:

163

reservation.buy_number(user.area_code)

169

sms_response_text = "You have successfully {0} the reservation".format(reservation.status)

170

reservation.notify_guest()

172

return twiml(_respond_message(sms_response_text))

175

@app.route('/exchange/sms', methods=["POST"])

179

outgoing_number = _gather_outgoing_phone_number(form.From.data, form.To.data)

181

response = MessagingResponse()

182

response.message(form.Body.data, to=outgoing_number)

186

@app.route('/exchange/voice', methods=["POST"])

189

outgoing_number = _gather_outgoing_phone_number(form.From.data, form.To.data)

191

response = VoiceResponse()

192

response.play("http://howtodocs.s3.amazonaws.com/howdy-tng.mp3")

193

response.dial(outgoing_number)

201

uri_pattern = request.url_rule

202

if current_user.is_authenticated and (

203

uri_pattern == '/' or uri_pattern == '/login' or uri_pattern == '/register'):

207

@login_manager.user_loader

210

return User.query.get(id)

215

def _gather_outgoing_phone_number(incoming_phone_number, anonymous_phone_number):

216

reservation = Reservation.query \

217

.filter(Reservation.anonymous_phone_number == anonymous_phone_number) \

221

raise Exception('Reservation not found for {0}'.format(incoming_phone_number))

223

if reservation.guest.phone_number == incoming_phone_number:

224

return reservation.vacation_property.host.phone_number

226

return reservation.guest.phone_number

229

def _respond_message(message):

230

response = MessagingResponse()

231

response.message(message)

Next, let's see how to connect the guest and the host via SMS.

Our TwiML application should be configured to send HTTP requests to this controller method on any incoming text message. Our app responds with TwiML to tell Twilio what to do in response to the message.

If the initial message sent to the anonymous number was sent by the host, we forward it on to the guest. Likewise, if the original message was sent by the guest, we forward it to the host.

We wrote a helper function called gather_outgoing_phone_number to help us determine which party to forward the message to.

1

from twilio.twiml.messaging_response import MessagingResponse

2

from twilio.twiml.voice_response import VoiceResponse

4

from airtng_flask import db, bcrypt, app, login_manager

5

from flask import g, request

6

from flask.ext.login import login_user, logout_user, current_user, login_required

8

from airtng_flask.forms import RegisterForm, LoginForm, VacationPropertyForm, ReservationForm, \

9

ReservationConfirmationForm, ExchangeForm

10

from airtng_flask.view_helpers import twiml, view, redirect_to, view_with_params

11

from airtng_flask.models import init_models_module

13

init_models_module(db, bcrypt, app)

15

from airtng_flask.models.user import User

16

from airtng_flask.models.vacation_property import VacationProperty

17

from airtng_flask.models.reservation import Reservation

20

@app.route('/', methods=["GET", "POST"])

21

@app.route('/register', methods=["GET", "POST"])

24

if request.method == 'POST':

25

if form.validate_on_submit():

27

if User.query.filter(User.email == form.email.data).count() > 0:

28

form.email.errors.append("Email address already in use.")

29

return view('register', form)

34

password=form.password.data,

35

phone_number="+{0}{1}".format(form.country_code.data, form.phone_number.data),

36

area_code=str(form.phone_number.data)[0:3])

40

login_user(user, remember=True)

42

return redirect_to('home')

44

return view('register', form)

46

return view('register', form)

49

@app.route('/login', methods=["GET", "POST"])

52

if request.method == 'POST':

53

if form.validate_on_submit():

54

candidate_user = User.query.filter(User.email == form.email.data).first()

56

if candidate_user is None or not bcrypt.check_password_hash(candidate_user.password,

58

form.password.errors.append("Invalid credentials.")

59

return view('login', form)

61

login_user(candidate_user, remember=True)

62

return redirect_to('home')

63

return view('login', form)

66

@app.route('/logout', methods=["POST"])

70

return redirect_to('home')

73

@app.route('/home', methods=["GET"])

79

@app.route('/properties', methods=["GET"])

82

vacation_properties = VacationProperty.query.all()

83

return view_with_params('properties', vacation_properties=vacation_properties)

86

@app.route('/properties/new', methods=["GET", "POST"])

89

form = VacationPropertyForm()

90

if request.method == 'POST':

91

if form.validate_on_submit():

92

host = User.query.get(current_user.get_id())

94

property = VacationProperty(form.description.data, form.image_url.data, host)

97

return redirect_to('properties')

99

return view('property_new', form)

102

@app.route('/reservations/', methods=["POST"], defaults={'property_id': None})

103

@app.route('/reservations/<property_id>', methods=["GET", "POST"])

105

def new_reservation(property_id):

108

form.property_id.data = property_id

110

if request.method == 'POST':

111

if form.validate_on_submit():

112

guest = User.query.get(current_user.get_id())

114

vacation_property = VacationProperty.query.get(form.property_id.data)

115

reservation = Reservation(form.message.data, vacation_property, guest)

116

db.session.add(reservation)

119

reservation.notify_host()

121

return redirect_to('properties')

123

if property_id is not None:

124

vacation_property = VacationProperty.query.get(property_id)

126

return view_with_params('reservation', vacation_property=vacation_property, form=form)

129

@app.route('/reservations', methods=["GET"])

132

user = User.query.get(current_user.get_id())

134

reservations_as_host = Reservation.query \

135

.filter(VacationProperty.host_id == current_user.get_id() and len(VacationProperty.reservations) > 0) \

136

.join(VacationProperty) \

137

.filter(Reservation.vacation_property_id == VacationProperty.id) \

140

reservations_as_guest = user.reservations

142

return view_with_params('reservations',

143

reservations_as_guest=reservations_as_guest,

144

reservations_as_host=reservations_as_host)

147

@app.route('/reservations/confirm', methods=["POST"])

148

def confirm_reservation():

149

form = ReservationConfirmationForm()

150

sms_response_text = "Sorry, it looks like you don't have any reservations to respond to."

152

user = User.query.filter(User.phone_number == form.From.data).first()

153

reservation = Reservation \

155

.filter(Reservation.status == 'pending'

156

and Reservation.vacation_property.host.id == user.id) \

159

if reservation is not None:

161

if 'yes' in form.Body.data or 'accept' in form.Body.data:

163

reservation.buy_number(user.area_code)

169

sms_response_text = "You have successfully {0} the reservation".format(reservation.status)

170

reservation.notify_guest()

172

return twiml(_respond_message(sms_response_text))

175

@app.route('/exchange/sms', methods=["POST"])

179

outgoing_number = _gather_outgoing_phone_number(form.From.data, form.To.data)

181

response = MessagingResponse()

182

response.message(form.Body.data, to=outgoing_number)

186

@app.route('/exchange/voice', methods=["POST"])

189

outgoing_number = _gather_outgoing_phone_number(form.From.data, form.To.data)

191

response = VoiceResponse()

192

response.play("http://howtodocs.s3.amazonaws.com/howdy-tng.mp3")

193

response.dial(outgoing_number)

201

uri_pattern = request.url_rule

202

if current_user.is_authenticated and (

203

uri_pattern == '/' or uri_pattern == '/login' or uri_pattern == '/register'):

207

@login_manager.user_loader

210

return User.query.get(id)

215

def _gather_outgoing_phone_number(incoming_phone_number, anonymous_phone_number):

216

reservation = Reservation.query \

217

.filter(Reservation.anonymous_phone_number == anonymous_phone_number) \

221

raise Exception('Reservation not found for {0}'.format(incoming_phone_number))

223

if reservation.guest.phone_number == incoming_phone_number:

224

return reservation.vacation_property.host.phone_number

226

return reservation.guest.phone_number

229

def _respond_message(message):

230

response = MessagingResponse()

231

response.message(message)

Let's see how to connect the guest and the host via phone call next.

Our Twilio application will send HTTP requests to this method on any incoming voice call. Our app responds with TwiML instructions that tell Twilio to Play an introductory MP3 audio file and then Dial either the guest or host, depending on who initiated the call.

1

from twilio.twiml.messaging_response import MessagingResponse

2

from twilio.twiml.voice_response import VoiceResponse

4

from airtng_flask import db, bcrypt, app, login_manager

5

from flask import g, request

6

from flask.ext.login import login_user, logout_user, current_user, login_required

8

from airtng_flask.forms import RegisterForm, LoginForm, VacationPropertyForm, ReservationForm, \

9

ReservationConfirmationForm, ExchangeForm

10

from airtng_flask.view_helpers import twiml, view, redirect_to, view_with_params

11

from airtng_flask.models import init_models_module

13

init_models_module(db, bcrypt, app)

15

from airtng_flask.models.user import User

16

from airtng_flask.models.vacation_property import VacationProperty

17

from airtng_flask.models.reservation import Reservation

20

@app.route('/', methods=["GET", "POST"])

21

@app.route('/register', methods=["GET", "POST"])

24

if request.method == 'POST':

25

if form.validate_on_submit():

27

if User.query.filter(User.email == form.email.data).count() > 0:

28

form.email.errors.append("Email address already in use.")

29

return view('register', form)

34

password=form.password.data,

35

phone_number="+{0}{1}".format(form.country_code.data, form.phone_number.data),

36

area_code=str(form.phone_number.data)[0:3])

40

login_user(user, remember=True)

42

return redirect_to('home')

44

return view('register', form)

46

return view('register', form)

49

@app.route('/login', methods=["GET", "POST"])

52

if request.method == 'POST':

53

if form.validate_on_submit():

54

candidate_user = User.query.filter(User.email == form.email.data).first()

56

if candidate_user is None or not bcrypt.check_password_hash(candidate_user.password,

58

form.password.errors.append("Invalid credentials.")

59

return view('login', form)

61

login_user(candidate_user, remember=True)

62

return redirect_to('home')

63

return view('login', form)

66

@app.route('/logout', methods=["POST"])

70

return redirect_to('home')

73

@app.route('/home', methods=["GET"])

79

@app.route('/properties', methods=["GET"])

82

vacation_properties = VacationProperty.query.all()

83

return view_with_params('properties', vacation_properties=vacation_properties)

86

@app.route('/properties/new', methods=["GET", "POST"])

89

form = VacationPropertyForm()

90

if request.method == 'POST':

91

if form.validate_on_submit():

92

host = User.query.get(current_user.get_id())

94

property = VacationProperty(form.description.data, form.image_url.data, host)

97

return redirect_to('properties')

99

return view('property_new', form)

102

@app.route('/reservations/', methods=["POST"], defaults={'property_id': None})

103

@app.route('/reservations/<property_id>', methods=["GET", "POST"])

105

def new_reservation(property_id):

108

form.property_id.data = property_id

110

if request.method == 'POST':

111

if form.validate_on_submit():

112

guest = User.query.get(current_user.get_id())

114

vacation_property = VacationProperty.query.get(form.property_id.data)

115

reservation = Reservation(form.message.data, vacation_property, guest)

116

db.session.add(reservation)

119

reservation.notify_host()

121

return redirect_to('properties')

123

if property_id is not None:

124

vacation_property = VacationProperty.query.get(property_id)

126

return view_with_params('reservation', vacation_property=vacation_property, form=form)

129

@app.route('/reservations', methods=["GET"])

132

user = User.query.get(current_user.get_id())

134

reservations_as_host = Reservation.query \

135

.filter(VacationProperty.host_id == current_user.get_id() and len(VacationProperty.reservations) > 0) \

136

.join(VacationProperty) \

137

.filter(Reservation.vacation_property_id == VacationProperty.id) \

140

reservations_as_guest = user.reservations

142

return view_with_params('reservations',

143

reservations_as_guest=reservations_as_guest,

144

reservations_as_host=reservations_as_host)

147

@app.route('/reservations/confirm', methods=["POST"])

148

def confirm_reservation():

149

form = ReservationConfirmationForm()

150

sms_response_text = "Sorry, it looks like you don't have any reservations to respond to."

152

user = User.query.filter(User.phone_number == form.From.data).first()

153

reservation = Reservation \

155

.filter(Reservation.status == 'pending'

156

and Reservation.vacation_property.host.id == user.id) \

159

if reservation is not None:

161

if 'yes' in form.Body.data or 'accept' in form.Body.data:

163

reservation.buy_number(user.area_code)

169

sms_response_text = "You have successfully {0} the reservation".format(reservation.status)

170

reservation.notify_guest()

172

return twiml(_respond_message(sms_response_text))

175

@app.route('/exchange/sms', methods=["POST"])

179

outgoing_number = _gather_outgoing_phone_number(form.From.data, form.To.data)

181

response = MessagingResponse()

182

response.message(form.Body.data, to=outgoing_number)

186

@app.route('/exchange/voice', methods=["POST"])

189

outgoing_number = _gather_outgoing_phone_number(form.From.data, form.To.data)

191

response = VoiceResponse()

192

response.play("http://howtodocs.s3.amazonaws.com/howdy-tng.mp3")

193

response.dial(outgoing_number)

201

uri_pattern = request.url_rule

202

if current_user.is_authenticated and (

203

uri_pattern == '/' or uri_pattern == '/login' or uri_pattern == '/register'):

207

@login_manager.user_loader

210

return User.query.get(id)

215

def _gather_outgoing_phone_number(incoming_phone_number, anonymous_phone_number):

216

reservation = Reservation.query \

217

.filter(Reservation.anonymous_phone_number == anonymous_phone_number) \

221

raise Exception('Reservation not found for {0}'.format(incoming_phone_number))

223

if reservation.guest.phone_number == incoming_phone_number:

224

return reservation.vacation_property.host.phone_number

226

return reservation.guest.phone_number

229

def _respond_message(message):

230

response = MessagingResponse()

231

response.message(message)

That's it! We've just implemented anonymous communications that allow your customers to connect while protecting their privacy.

If you're a Python developer working with Twilio you might want to check out these other tutorials:

IVR: Phone Tree

Create a seamless customer service experience by building an IVR Phone Tree for your company.

Call Tracking

Measure the effectiveness of different marketing campaigns by assigning a unique phone number to different advertisements and track which ones have the best call rates while getting some data about the callers themselves.

Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Tweet @twilio (link takes you to an external page) to let us know what you think.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4