python - Google App Engine TextProperty 和 UTF-8 : When to Encode/Decode

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

我在使用 Django 模板和 Webapp 框架的 Google App Engine 2.5。

db.TextProperty 和 UTF-8 以及 Unicode 和解码/编码让我很困惑。我真的很感激一些专家可以提供一些建议。我在谷歌上搜索了一整晚,仍然有很多问题。

我正在尝试做的事情:

[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')})

希望有谷歌应用引擎工程师能看到这个问题并提供帮助。非常感谢!

最佳答案

首先,read this . And this .

简而言之,只要您在应用中处理文本字符串,它就应该是 unicode 字符串。当你想将数据作为字节发送时,你应该编码成一个字节字符串('str' 的一个实例而不是'unicode') - 例如,通过 HTTP,当你接收到代表文本的字节时,你应该从字节字符串解码(你知道他们的编码)。您应该对包含编码文本的字节字符串执行的唯一操作是对其进行解码或编码。

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

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

永远不要尝试解码 unicode 字符串,或编码字节字符串;它不会按照您的预期进行,而且会出现可怕的错误。

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

关于python - Google App Engine TextProperty 和 UTF-8 : When to Encode/Decode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10766472/

相关文章:

google-app-engine - 为什么 Google 应用引擎将 URL、电话号码等识别为特殊数据类型?

javascript - 谁执行 unicode 规范化以及何时执行?

python - CSR scipy 矩阵在更新其值后不会更新

python - 如何在 Python 中序列化哈希对象

python - pandas 不同列中唯一值的频率

google-app-engine - 使用 Ktor 进行部署 : How To Set AppEngine Version?

java - 有像 JPA 3 这样的版本吗?

c++ - 生成一个随机的unicode字符串

c++ - C++11 中的 Unicode

python - 使用 DataFrame.plot 制作带子图的图表 -- 如何使用 ax 参数