Python,Google App Engine错误:断言类型(数据)是StringType,"write()参数必须是字符串"

Jul*_*les 3 python google-app-engine

我现在正在学习Google App Engine,其中有一本书是"使用Charles Severance的Google App Engine".

我在第6章,到目前为止,我已经取得app.yaml,index.py,index.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()
Run Code Online (Sandbox Code Playgroud)

为什么我收到此错误?

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
Run Code Online (Sandbox Code Playgroud)

小智 5

由于一些旧的Google App Engine示例代码,我最近也遇到了这个确切的错误.我的问题是在doRender()函数中,outstr对象是一个django.utils.safestring.SafeUnicode对象,因此write()函数抱怨.所以我把它传递unicode()给了一个可以使用的unicode对象write().

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
Run Code Online (Sandbox Code Playgroud)