首页 > 解决方案 > Twilio 错误 - 11200 HTTPS 检索/Python Flask 应用程序

问题描述

我从下面的代码中收到 11200 HTTPS 检索错误。有人可以解释一下我该如何解决这个问题吗?(我将此应用程序托管在本地服务器上,并使用 ngrok https 5000 URL 作为 twilio API)

from flask import Flask, Response, request
from twilio import twiml
import os
from twilio.http.http_client import TwilioHttpClient
import requests
from twilio.rest import Client


app = Flask(__name__)
port = int(os.environ.get('PORT', 5000))


account_sid = "xxx"
auth_token = "xxx"

# proxy_client = TwilioHttpClient(proxy={'http': os.environ['http_proxy'], 'https': os.environ['https_proxy']})
client = Client(account_sid, auth_token)


@app.route("/")
def check_app():
    # returns a simple string stating the app is working
    return Response("It works!"), 200


@app.route("/twilio", methods=["POST"])
def inbound_sms():
    response = twiml.Response()
    # we get the SMS message from the request. we could also get the 
    # "To" and the "From" phone number as well
    inbound_message = request.form.get("Body")

    print(inbound_message)
    # we can now use the incoming message text in our Python application
    if inbound_message == "Hello":
        response.message("Hello back to you!")
    else:
        response.message("Hi! Not quite sure what you meant, but okay.")
    # we return back the mimetype because Twilio needs an XML response
    return Response(str(response), mimetype="application/xml"), 200


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

标签: pythonflaskherokuhttpstwilio

解决方案


您混淆了 Flask 响应和 Twilio 响应,您的代码实际上是AttributeError在 Python 3.6.9 下使用 Twilio Python Helper Library 版本 6.45.1 引发的,因为 Twilio 没有twiml.Response属性。

将您的代码更改为以下内容,请注意以下用法MessagingResponse

@app.route("/twilio", methods=["POST"])
def inbound_sms():
    response = MessagingResponse()
    inbound_message = request.form.get("Body")
    if inbound_message == "Hello":
        response.message("Hello back to you!")
    else:
        response.message("Hi! Not quite sure what you meant, but okay.")
    return Response(str(response), mimetype="application/xml"), 200

不要忘记添加from twilio.twiml.messaging_response import MessagingResponse到您的导入中。另请参阅Twilio 文档中的示例

我只在本地对其进行了测试,但是/twilio当您使用 HTTPie 访问它时,您的端点会返回正确的TwiML

$ http --form POST http://127.0.0.1:5000/twilio Body=Hello
HTTP/1.0 200 OK
Content-Length: 96
Content-Type: application/xml; charset=utf-8
Date: Fri, 26 Feb 2021 12:15:30 GMT
Server: Werkzeug/1.0.1 Python/3.6.9

<?xml version="1.0" encoding="UTF-8"?><Response><Message>Hello back to you!</Message></Response>

推荐阅读