Google App Engine TextProperty和UTF-8:何时进行编码/解码

时间:2012-05-26 13:02:30

标签: python google-app-engine unicode utf-8

我使用Django模板和Webapp Frame在Google App Engine 2.5上。

db.TextProperty和UTF-8以及Unicode和Decode / Encode让我非常困惑。我真的很感谢一些专家可以提供一些建议。我用Google搜索了一整夜,但仍有很多问题。

我想做什么:

[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工程师可以看到这个问题并提供一些帮助。非常感谢!

2 个答案:

答案 0 :(得分:1)

首先,read thisAnd this

简而言之,每当您在应用程序中处理文本字符串时,它应该是一个unicode字符串。当您希望以字节形式发送数据时(例如,通过HTTP),您应该编码为字节字符串('str'而不是'unicode'的实例),并且当您接收表示文本的字节时,您应该从字节字符串解码(你知道他们的编码)。您应该对包含编码文本的字节字符串执行的唯一操作是对它们进行解码或编码。

幸运的是,大多数框架都是正确的;例如,webapp和webapp2(我可以看到你正在使用webapp)应该从所有请求方法返回unicode字符串,并对你传递给它们的任何字符串进行适当的编码。确保你负责的所有字符串都是unicode,你应该没问题。

请注意,字节字符串可以存储任何类型的数据 - 编码文本,可执行文件,图像,随机字节,加密数据等。如果没有元数据,例如它的文本知识和它的编码,除了存储和检索它之外,你不能明智地做任何事情。

不要尝试解码unicode字符串,也不要编码字节字符串;它不会做你期望的事情,事情会发生可怕的错误。

关于数据存储区,db.Textunicode的子类;对于所有意图和目的,它一个unicode字符串 - 它只是不同,所以数据存储可以告诉它不应该被索引。同样,db.Blobstr的子类,用于存储字节字符串。

答案 1 :(得分:0)

尝试

db.Text("text", encoding="utf-8")

它帮助我将utf-8文本保存到TextProperty()

详情请参阅以下链接: https://developers.google.com/appengine/docs/python/datastore/typesandpropertyclasses?hl=en#Text