Twilo python Flask传递参数

时间:2019-07-01 18:18:49

标签: python flask twilio

我有一个可以运行python的应用程序,但是我想将语音识别的结果传递给我不知道如何的呼叫者,我已经尝试了一切。我什至试图通过在顶部声明lastRes不起作用来将lastRes设置为全局变量

lastRes = ""
app = Flask(__name__)

@app.route("/voice", methods=['GET', 'POST'])
def voice():
  resp = VoiceResponse()
  resp.say("What is your name?")
  print ("1---------------")
  resp.gather(input='speech', timeout="3", action='/gather', method='POST')
  #resp.append(gather)
  print ("2---------------")
  return str(resp)

@app.route("/mainFlow", methods=['GET', 'POST'])
def mainFlow():
  resp = VoiceResponse()
  resp.say("We are done?")
  print("5--------------->" + str(lastRes))
  return str(resp)

@app.route("/gather", methods=['GET', 'POST'])
def gather():
  resp = VoiceResponse()
  print("3---------------")
  lastRes = request.values.get("SpeechResult", "")
  print("4--------------->" + str(lastRes))
  resp.redirect('/mainFlow')
  return str(resp)

if __name__ == "__main__":
  lastRes = ""
  app.run(debug=True)

如何将lastRes传递给例程/ mainFlow?

1 个答案:

答案 0 :(得分:3)

这里是Twilio开发人员的传播者。

首先,我想问一下为什么要在使用结果之前尝试重定向。您在/gather端点中已经有语音结果,为什么不响应呢?像这样:

@app.route("/gather", methods=['GET', 'POST'])
def gather():
  resp = VoiceResponse()
  lastRes = request.values.get("SpeechResult", "")
  resp.say('Thank you ' + lastRes + '.')
  resp.redirect('/mainFlow')
  return str(resp)

此响应将说出“谢谢”,然后说出语音结果,然后重定向到主流。

或者,您正在使用URL。您可以将响应设置为URL参数,如下所示:

import urllib

@app.route("/gather", methods=['GET', 'POST'])
def gather():
  resp = VoiceResponse()
  SpeechResult = request.values.get("SpeechResult", "")
  params = urllib.urlencode({"SpeechResult": SpeechResult})
  resp.redirect('/mainFlow?' + params)
  return str(resp)

然后,您可以像下面这样在SpeechResult中使用mainFlow

@app.route("/mainFlow", methods=['GET', 'POST'])
def mainFlow():
  SpeechResult = request.args.get('SpeechResult')
  resp = VoiceResponse()
  resp.say("We are done? " + SpeechResult)
  return str(resp)

最后,您也可以在会话中设置SpeechResult,因为在通话过程中也可以保持该结果。

from flask import Flask, session, request

@app.route("/gather", methods=['GET', 'POST'])
def gather():
  resp = VoiceResponse()
  session['SpeechResult'] = request.values.get("SpeechResult", "")
  resp.redirect('/mainFlow')
  return str(resp)

@app.route("/mainFlow", methods=['GET', 'POST'])
def mainFlow():
  SpeechResult = session['SpeechResult']
  resp = VoiceResponse()
  resp.say("We are done? " + SpeechResult)
  return str(resp)

让我知道是否有帮助。