1

我在 Google App Engine 上使用 webapp2 框架,但在我的一个请求处理程序中遇到了一个基本错误。

该应用在本地实例中运行正常,但在已部署的 Google App Engine 版本上导致以下回溯:

这是代码:

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

这个错误是什么意思?

4

1 回答 1

2

我认为响应不采用 unicode 数据,因此您必须先对其进行编码

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

我也推荐Werkzeug。它在 appengine 上运行良好,让生活变得如此轻松。它有助于处理请求和响应数据、url 路由、提供 http 异常、具有出色的离线开发调试器等等。我认为 Werkzeug 是每个 Python Web 开发人员工具箱中的必备工具。

于 2011-12-19T13:37:14.697 回答