我可以在不使用面向对象的python中使用Flask运行twilo。在Twilo仪表板中,我使用webhook并设置:https://123456.ngrok.io/voice 而且效果很好。
但是我想使代码面向对象,以便可以全局使用语音识别的结果。
我尝试了这个,但是当Twilo到达我的代码时,我得到了这个错误
127.0.0.1 - - [01/Jul/2019 08:59:05] "POST /voice HTTP/1.1" 404 -
这是我的代码,为什么找不到/ voice
app = Flask(__name__)
class MyServer(Flask):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@app.route("/voice", methods=['GET', 'POST'])
def voice(self):
self.resp = VoiceResponse()
self.resp.say("What is your name?")
print("1---------------")
self.resp.gather(input='speech', timeout="3", action='/gather', method='POST')
# resp.append(gather)
print("2---------------")
# print (str(resp))
# resp.say("Thank you for telling us your name")
return str(self.resp)
@app.route("/gather", methods=['GET', 'POST'])
def gather(self):
self.resp = VoiceResponse()
print("3---------------")
self.speechRecogRes = request.values.get("SpeechResult", "")
print("4--------------->" + str(self.speechRecogRes))
self.resp.redirect('/voice')
return str(self.resp)
if __name__ == '__main__':
print('Hello!!')
app = MyServer(__name__)
app.run(debug=True)
我什至尝试将Twilo仪表板中的Webhook地址更改为self.voice:
https://123456.ngrok.io/self.voice
但这不起作用
答案 0 :(得分:2)
这里是Twilio开发人员的传播者。
很抱歉,我不是Python开发人员,在这里我没有完整的答案。我可以尝试引导您走上正确的道路。
首先,在您的MyServer
类中,您正在使用@app.route
装饰器,但是没有app
对象要处理。
据我对Flask文档的了解,可以对Flask进行子类化,但这只是为了使其在服务器级别具有不同的行为。
我相信,当您要将Flask应用程序模块化时,您实际上要研究Blueprints。如果您想遵循Flask的做事方式,那可能是最好的选择。
但是,如果您以这样的子类出售,那么我可以找到的成功使用此类的最佳示例是GitHub gist:https://gist.github.com/dplepage/2024129。它没有任何评论,但希望它是相对自我解释的。这个想法是,您需要在构造函数中使用self.route
进行路由。
因此对于您的应用,可能看起来像这样(未经测试):
class MyServer(Flask):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.route('/voice', self.voice, methods=['GET', 'POST'])
self.route('/gather', self.gather, methods=['GET', 'POST'])
def voice(self):
self.resp = VoiceResponse()
self.resp.say("What is your name?")
print("1---------------")
self.resp.gather(input='speech', timeout="3", action='/gather', method='POST')
# resp.append(gather)
print("2---------------")
# print (str(resp))
# resp.say("Thank you for telling us your name")
return str(self.resp)
def gather(self):
self.resp = VoiceResponse()
print("3---------------")
self.speechRecogRes = request.values.get("SpeechResult", "")
print("4--------------->" + str(self.speechRecogRes))
self.resp.redirect('/voice')
return str(self.resp)
if __name__ == '__main__':
print('Hello!!')
app = MyServer(__name__)
app.run(debug=True)