Python、Google App Engine 错误 : assert type(data) is StringType ,"write() argument must be string"

标签 python google-app-engine

我现在正在通过一本名为“Charles Severance 的 Using Google App Engine”的书来学习 Google App Engine。

我在第 6 章,到目前为止我已经在模板文件夹中制作了 app.yamlindex.pyindex.html 和静态文件夹中的 CSS 文件。

我的 index.py 看起来像这样:

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

class MainHandler(webapp.RequestHandler):
      def get(self):
          path=self.request.path
          temp=os.path.join(os.path.dirname(__file__, 'templates' + path)
          if not os.path.isfile(temp):
             temp=os.path.join(os.path.dirname(__file__, 'templates/index.html')

          self.response.out.write(template.render(temp,{}))

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

if __name == '__main__':
   main()

为什么会出现此错误?

Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 86, in run
    self.finish_response()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 127, in finish_response
    self.write(data)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 202, in write
    **assert type(data) is StringType,"write() argument must be string"**

AssertionError: write() argument must be string

最佳答案

由于一些旧的 Google App Engine 示例代码,我最近也遇到了这个确切的错误。我的问题出在 doRender() 函数中,其中 outstr 对象是一个 django.utils.safestring.SafeUnicode 对象,因此 write() 函数在提示。所以我通过 unicode() 传递它,最终得到 write() 可以接受的 unicode 对象。

def doRender(handler, tname="index.html", values={}):
    temp = os.path.join(os.path.dirname(__file__),
                        'templates/' + tname)
    if not os.path.isfile(temp):
        return False

    # Make a copy of the dictionary and add the path
    newval = dict(values)
    newval['path'] = handler.request.path

    outstr = template.render(temp, newval)
    handler.response.out.write(unicode(outstr))
    return True

关于Python、Google App Engine 错误 : assert type(data) is StringType ,"write() argument must be string",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16004135/

相关文章:

java - 如何连接到本地谷歌云数据存储数据库?

python - 从 python webapp2 Google App Engine 发送电子邮件

c# - MySqlConnectionStringBuilder - 连接证书

python - 是否可以 "dynamically"在 Python 中创建局部变量?

python - 如何在 opencv 中使用自适应阈值将阈值设置为零?

python - PySpark - 显示数据框中列数据类型的计数

google-app-engine - 有没有办法知道一组应用程序引擎任务队列任务何时完成?

python - 为什么此代码不生成具有随机颜色的形状?

python - ctypes.windll.user32.GetKeyState 无法识别按键

node.js - Google App Engine - 指定自定义构建依赖项