Google App Engine 上 Python 中的 Unicode
我需要发出一个 POST 请求,其中的数据可能是非 ASCII(中文、日文字符)。 我需要将输入转换为 unicode 并使用 utf-8 进行编码。我是这样做的:
foo = unicode(self.request.get('foo'), 'utf-8') #convert to unicode
foo = foo.encode('utf-8') #encode with utf-8
data = {'foo': foo}
payload = urllib.urlencode(data)
但是,我不断在日志中收到此错误:
类型错误:无法解码 Unicode 支持
I need to make a POST request in which the data might be non-ascii (chinese, japanese characters).
I need to convert the input to unicode and encode with utf-8. Here's how I did it:
foo = unicode(self.request.get('foo'), 'utf-8') #convert to unicode
foo = foo.encode('utf-8') #encode with utf-8
data = {'foo': foo}
payload = urllib.urlencode(data)
However, I keep getting this error in my logs:
TypeError: decoding Unicode is not
supported
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Unicode 无法解码,因为它已经是 unicode。
试试这个:
Unicode can't be decoded because it's already unicode.
Try this instead:
好的一些评论:
不要称之为“转换”。称之为“解码”,这样就更清楚了。
但为什么?您刚刚从 UTF8 解码了它,为什么还要将其编码回来?你也可以这样做:
这相当于上面两行。
为了减少您对 Unicode 的困惑,请阅读以下内容:http://www.joelonsoftware.com/articles/Unicode .html
Ok some comments:
Don't call it "convert". Call it "decode", it makes it clearer.
But why? You just decoded it from UTF8, why are you encoding it back? You can just as well do:
That's equivalent to the above two lines.
To lessen your confusion on Unicode, read this: http://www.joelonsoftware.com/articles/Unicode.html