2011-12-19 82 views
1

我在Google App Engine上使用webapp2框架,並在我的一個請求處理程序中收到基本錯誤。使用Webapp2部署的GAE RequestHandler中的錯誤

應用程序是運行在本地實例確定,但會導致對谷歌的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 

這個錯誤是什麼意思?

回答

2

我想響應不採取Unicode數據,所以你必須encode首先:

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

此外,我建議Werkzeug。它在appengine上運行良好,使生活變得如此簡單。它有助於處理請求和響應數據,URL路由,提供http異常,對離線開發和更多的調試器。我認爲Werkzeug是他們工具箱中每個python web開發人員必須擁有的。

+0

感謝您的回答。通常使用GAE,我從來不需要編碼到utf-8中。但是,您的答案確實讓我想起了爲響應呈現的html文件。我的代碼編輯器已經自動插入html標記,使html轉換爲utf-8。這是我第一次將這個標記加入到html文件中,也是我第一次看到這個特定的錯誤。但是,唉,同樣的錯誤重複自己與該標記或不。並按照你的建議編碼,沒有它。然而,我贊成你的回答,因爲我認爲這是一個好的預感,可以讓其他人受益。任何其他想法? – 2011-12-19 17:44:42

+1

我剛剛通過將渲染的模板值轉換爲字符串來重試此操作,並且它工作正常。不知道是什麼原因,因爲這是我第一次這樣做。通常在我之前的應用程序中,以及GAE文檔中的所有示例中,template.render(路徑,值)按原樣運行。再次感謝您指向我的文本編碼方向! – 2011-12-19 17:53:42

+0

Jinja2不支持utf-8字節串。 'Template.render'總是返回unicode字符串。如果您將非Unicode字符的非Unicode字符傳遞給JINJA模板,您將得到Unicode錯誤。 – Ski 2011-12-19 20:32:53