2009/03/27

Google App Engine 程式中文問題


  架好開發環境,也寫好最簡單的第一支 helloworld.py 之後,很容易地就上傳到 Google App Engine 正確執行.但是,問題來了,那支程式太簡單了,而且是英文.一來加入就正確的寫法,二來測試中文是否正確顯示,果然問題出現了! 執行畫面如上圖:

以下是程式碼:

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, webapp World! 中文')
self.response.out.write("我是中文")

application = webapp.WSGIApplication([('/', MainPage)],debug=True)

def main():
run_wsgi_app(application)

if __name__ == "__main__":
main()


  想了一下開發語言 Python 針對中文需要注意的地方,才發現在最前面加入一行 encoding


# -*- coding: utf-8 -*-

  結果還是不行,接下來就想到 Content-Encoding 上面了,可惜 Google App Engine (GAE) 文件上有說明,基於安全考量,設定 Content-Encoding 是無效的.最後,把Content-Type 由 text/plain 改成 text/html 後中文亂碼問題就解決了 !

  以下是完整程式碼:



# -*- coding: utf-8 -*-
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write('Hello, webapp World! 中文')
self.response.out.write("我是中文"
self.response.out.write("單引號或雙引號括起來都可以 !")
self.response.out.write("記得第一行加入 # -*- coding: utf-8 -*-")
self.response.out.write("記得Content-Type 設為 text/html")

application = webapp.WSGIApplication([('/', MainPage)],debug=True)

def main():
run_wsgi_app(application)

if __name__ == "__main__":
main()