3

我现在正在通过 Charles Severance 的《使用 Google App Engine》一书学习 Google App Engine。

我在第 6 章,到目前为止,我已经在模板文件夹中制作了app.yaml, index.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
4

2 回答 2

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
于 2013-04-15T16:36:52.683 回答
0

第 2 行:更改import wsgiref.appengine.ext import webappimport wsgiref.

第 9 行:添加一个)之后__file__

第 11 行:添加一个)之后__file__

第 19 行:更改__name__name__

这些都是基本的语法错误。你刚才抄错书了。始终通过 App Engine SDK 提供的开发服务器 dev_appserver.py 运行新代码。

于 2013-04-15T03:39:01.540 回答