首页 > 解决方案 > python Flask和类和面向对象的twilio

问题描述

我可以在没有面向对象的情况下在 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 Dashboard 中的 webhook 地址更改为 self.voice:

https://123456.ngrok.io/self.voice

但它不起作用

标签: pythonflasktwilio

解决方案


Twilio 开发人员布道者在这里。

对不起,我不是 Python 开发人员,在这里我没有完整的答案。不过,我可以尝试引导您走上正确的道路。

首先,在您的MyServer班级中,您正在使用@app.route装饰器,但没有app要处理的对象。

据我查看 Flask 文档可知,您可以将 Flask 子类化,但这只是为了在服务器级别赋予它不同的行为。

我相信,当您想要模块化 Flask 应用程序时,您实际上想要查看Blueprints。如果你想遵循 Flask 的做事方式,那可能是你最好的选择。


但是,如果您对这样的子类化感到满意,那么我能找到的成功使用此类类的最佳示例就是这个 GitHub 要点: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)

推荐阅读