2013-04-14 16 views
3

我现在正在学习一本书“使用Google App Engine by Charles Severance”。Python,Google App Engine错误:断言类型(数据)是StringType,“write()参数必须是字符串”

我在第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() 

为什么我得到这个错误?

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 

回答

5

由于一些旧的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 
+0

我试过unicode,但没有成功。然后我试着把str作为一个字符串来输出,然后它就起作用了!谢谢您的回复! – Jules

+0

为我完美工作! – rogcg

0

线路2:改变import wsgiref.appengine.ext import webappimport wsgiref

9号线:添加)__file__

线11:添加)__file__

第19行:改变__name__name__

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

+0

谢谢您的回复!我实际上在文本编辑器上输入了正确的内容,但是在我的文章中复制了非常错误。我当然应该更加注意细节!再次感谢。 – Jules

相关问题