【问题标题】:Error in deployed GAE RequestHandler using Webapp2使用 Webapp2 部署 GAE RequestHandler 时出错
【发布时间】:2012-01-23 09:44:15
【问题描述】:

我在 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

这个错误是什么意思?

【问题讨论】:

    标签: google-app-engine webapp2


    【解决方案1】:

    我认为响应不采用 unicode 数据,所以你必须先encode它:

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

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

    【讨论】:

    • 感谢您的回答。通常使用 GAE,我从来不需要编码成 utf-8。但是,您的回答确实让我想到了为响应呈现的 html 文件。我的代码编辑器已自动插入 html 标记以将 html 转换为 utf-8。那是我第一次将该标记放入 html 文件中,也是我第一次看到这个特殊错误。但是,同样的错误是否会在该标记中重复出现。并按照您的建议进行编码并且没有它。但是,我赞成您的回答,因为我认为这是一个可以使他人受益的好预感。还有其他想法吗?
    • 我刚刚通过将渲染的模板值转换为字符串来重试此操作,它工作正常。但是不确定是什么原因,因为这是我第一次必须这样做。通常在我以前的应用程序以及 GAE 文档的所有示例中,template.render(path,values) 都可以正常工作。再次感谢您为我指明文本编码方向!
    • Jinja2 不支持 utf-8 字节串。 Template.render 总是返回 unicode 字符串。如果您将带有非 ascii 字符的非 unicode 字符串传递给 jinja 模板,您将收到 unicode 错误。
    猜你喜欢
    • 1970-01-01
    • 2019-04-10
    • 2017-02-21
    • 1970-01-01
    • 2019-04-11
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多