Error in deployed GAE RequestHandler using Webapp2

2019-05-29 06:44发布

I am using the webapp2 framework on Google App Engine, and I'm getting a basic error in one of my Request Handlers.

The app is running ok in the local instance, but causes the following traceback on the deployed version of Google App Engine:

Here's the code:

import os
from google.appengine.ext.webapp import template
import webapp2
import logging 

class MainHandler(webapp2.RequestHandler):
    def get(self):
        logging.info('hi there 34')
        template_values = {}
        self.response.out.write('hello world 4')
        path = os.path.join(os.path.dirname(__file__), 'index.html')

        ## This is the code that causes the bug ##
        self.response.out.write(template.render(path, template_values))
        ## ## ## ##

debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')

app = webapp2.WSGIApplication(
    [(r'/main', MainHandler)], 
    debug = debug)

def main():
    app.run()

traceback error:

Traceback (most recent call last):

File "/base/python27_runtime/python27_dist/lib/python2.7/wsgiref/handlers.py", 
line 86, in run

self.finish_response()
File "/base/python27_runtime/python27_dist/lib/python2.7/wsgiref/handlers.py", 
line 127, in finish_response

self.write(data)

File "/base/python27_runtime/python27_dist/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

What does this error mean?

1条回答
Lonely孤独者°
2楼-- · 2019-05-29 07:47

I think response does not take unicode data, so you have to encode it first:

content = template.render(path, template_values)
self.response.out.write(content.encode('utf-8'))

Also I recommend Werkzeug. It works well on appengine and makes life so much easier. It helps to deal with request and response data, url routing, provides http exceptions, has great debugger for offline development and more. I think Werkzeug is a must to have for every python web dev in their toolbox.

查看更多
登录 后发表回答