【问题标题】:Google App Engine TextProperty and UTF-8: When to Encode/DecodeGoogle App Engine TextProperty 和 UTF-8:何时编码/解码
【发布时间】: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-8charset=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


【解决方案1】:

首先,read thisAnd this.

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

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

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

永远不要尝试解码 unicode 字符串或编码字节字符串;它不会像你期望的那样做,事情会变得非常糟糕。

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

【讨论】:

    【解决方案2】:

    试试

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-11-13
      • 2016-03-10
      • 2011-10-29
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 2012-11-07
      • 2014-01-24
      • 2013-03-26
      相关资源
      最近更新 更多