【发布时间】:2012-05-26 13:02:30
【问题描述】:
我正在使用带有 Django 模板和 Webapp 框架的 Google App Engine 2.5。
db.TextProperty 和 UTF-8 以及 Unicode 和 Decode/Encode 让我非常困惑。我真的很感谢一些专家可以提供一些建议。谷歌搜索了一晚上,还有很多问题。
我想做什么:
[utf-8 form input] => [Python, Store in db.TextProperty] => [When Needed, Replace Japanese with English] => [HTML, UTF-8]
根据这个回答Zipping together unicode strings in Python
# -*- coding: utf-8 -*-
以及所有以 utf-8 格式保存的 .py 文件
这是我的代码:
#Model.py
class MyModel(db.Model):
content = db.TextProperty()
#Main.py
def post(self):
content=cgi.escape(self.request.get('content'))
#what is the type of content? Unicode? Str? or Other?
obj = MyModel(content=content)
#obj = MyModel(content=unicode(content))
#obj = MyModel(content=unicode(content,'utf-8'))
#which one is the best?
obj.put()
#Replace one Japanese word with English word in the content
content=obj.content
#what is the type of content here? db.Text? Unicode? Str? or Other?
#content=unicode(obj.content, 'utf-8') #Is this necessary?
content=content.replace(u'ひと',u'hito')
#Output to HTML
self.response.out.write(template.render(path, {'content':content})
#self.response.out.write(template.render(path, {'content':content.encode('utf-8')})
希望一些 Google App Engine 工程师可以看到这个问题并提供一些帮助。非常感谢!
【问题讨论】:
-
嗨,苏珊。有趣的问题,但您可能希望包含更多详细信息,例如您用于存储数据的编码以及使用哪种语言(英语或日语)?如果是日语,您使用的是 UTF-8 还是其他?你总是以 UTF-8 格式输入还是混合搭配?您可以提供的任何更多详细信息都可以帮助您获得答案。祝你好运!
-
作为起点,您可以使用内置函数
type获取content变量类型:type(content)会告诉您cgi.escape返回的类型 -
@jmort253 我打算将所有内容保留为
UTF-8格式。 HTML 表单位于UTF-8和charset=utf-8中,没有使用其他编码。 -
您不需要(或不想)致电
cgi.escape。永远。 -
@Nick 嗯?不需要使用
cgi.escape?所以请告诉我:self.response.out.write(cgi.escape(self.request.get('content')))来自developers.google.com/appengine/docs/python/gettingstarted/… 是什么
标签: python google-app-engine unicode utf-8