0

我正在尝试创建一个演示网络服务器,该服务器根据 URL 提供的参数返回一个 TwiML Say 块,其中包含自定义文本(是的,POST 会更好,但我不太确定该怎么做)。它的工作原理很像https://www.twilio.com/labs/twimlets/message,只是我想编写自己的代码,以便添加更多自定义项。

我从构建电话天气演示开始,因为它在 xml 中包含自定义文本。

我创建了自己的名为 gracklevoice 的谷歌应用程序引擎,并且让 weatherbyphone 示例正常工作。现在,当我尝试简化它时遇到了麻烦。我的代码如下所示:

import os
import wsgiref.handlers

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp

BASE_URL = "http://gracklevoice.appspot.com/"


def xml_response(handler, page, templatevalues=None):
    """                                                                                          
    Renders an XML response using a provided template page and values                            
    """
    path = os.path.join(os.path.dirname(__file__), page)
    handler.response.headers["Content-Type"] = "text/xml"
    handler.response.out.write(template.render(path, templatevalues))

class GracklePage(webapp.RequestHandler):

    def get(self):
        self.post()

    def post(self):
        xml_response(self, 'notification.xml')

def main():
    application = webapp.WSGIApplication([ \
        ('/', GracklePage)],
        debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()

还有yaml文件:

application: gracklevoice
version: 1
runtime: python27
api_version: 1
threadsafe: no

handlers:
- url: /.*
  script: gracklevoice.py

和notification.xml

<?xml version="1.0" encoding="UTF-8"?>
<Response>
     <Say voice="alice" language="en-US">                                                             
     This is a message from Grackle.                                                                  
     </Say>
</Response>

这看起来应该很简单,但是当我的客户端应用程序将呼叫 url 设置为http://gracklevoice.appspot.com/时,我收到一个错误而不是语音消息:“我们很抱歉。发生了应用程序错误。再见。” 我错过了什么?

查看 appEngine 日志(长度有限,welp),我看到:

2013-11-18 14:45:09.781
Traceback (most recent call last):
E 2013-11-18 14:45:09.781
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/wsgiref/handlers.py", line 86, in run
E 2013-11-18 14:45:09.781
    self.finish_response()
E 2013-11-18 14:45:09.781
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/wsgiref/handlers.py", line 128, in finish_response
E 2013-11-18 14:45:09.781
    self.write(data)
E 2013-11-18 14:45:09.781
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/wsgiref/handlers.py", line 204, in write
E 2013-11-18 14:45:09.781
    assert type(data) is StringType,"write() argument must be string"
E 2013-11-18 14:45:09.781
AssertionError: write() argument must be string
4

1 回答 1

0

Twilio 开发人员布道者在这里。template.render(path, templatevalues)使用 unicode() 函数转换输出。您的新代码行将结束为

handler.response.out.write(unicode(template.render(path, templatevalues)))

template.render 函数的输出是 StringType,而不是 str 类型,这是 write 函数需要的。使用 unicode 函数进行转换会将输出转换为您需要的输入格式。

此问题中有关于 StringType 和 unicode 问题的其他信息。

于 2014-01-13T23:34:18.267 回答