Jules
Jules

Reputation: 105

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

I'm learning Google App Engine right now with a book 'Using Google App Engine by Charles Severance'.

I am on chapter 6 and so far I have made app.yaml, index.py, index.html in templates folder and the CSS file in the static folder.

My index.py looks like this:

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()

Why am I am getting this error?

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

Upvotes: 3

Views: 1964

Answers (2)

Carlos Pero
Carlos Pero

Reputation: 94

I ran into this exact error recently as well, due to some old Google App Engine sample code. My problem was in the doRender() function, where the outstr object was a django.utils.safestring.SafeUnicode object, and thus the write() function was complaining. So I passed it through unicode() to end up with a unicode object that write() was okay with.

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

Upvotes: 5

Dave
Dave

Reputation: 3570

Line 2: change import wsgiref.appengine.ext import webapp to import wsgiref.

Line 9: add an ) after __file__

Line 11: add an ) after __file__

Line 19: change __name to __name__

These are all basic syntax errors. You just copied from the book wrong. Always run new code through dev_appserver.py, the development server provided by the App Engine SDK.

Upvotes: 0

Related Questions