Google App Engine 上 Python 中的 Unicode

发布于 2024-10-09 05:59:11 字数 388 浏览 0 评论 0原文

我需要发出一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晨曦慕雪 2024-10-16 05:59:11

Unicode 无法解码,因为它已经是 unicode。

试试这个:

if isinstance(var, str):
    var = unicode(var, 'utf-8')
else:
    var = unicode(var)

Unicode can't be decoded because it's already unicode.

Try this instead:

if isinstance(var, str):
    var = unicode(var, 'utf-8')
else:
    var = unicode(var)
情深缘浅 2024-10-16 05:59:11

好的一些评论:

 foo = unicode(self.request.get('foo'), 'utf-8') #convert to unicode

不要称之为“转换”。称之为“解码”,这样就更清楚了。

 foo = foo.encode('utf-8')                       #encode with utf-8

但为什么?您刚刚从 UTF8 解码了它,为什么还要将其编码回来?你也可以这样做:

 foo = self.request.get('foo')

这相当于上面两行。

为了减少您对 Unicode 的困惑,请阅读以下内容:http://www.joelonsoftware.com/articles/Unicode .html

Ok some comments:

 foo = unicode(self.request.get('foo'), 'utf-8') #convert to unicode

Don't call it "convert". Call it "decode", it makes it clearer.

 foo = foo.encode('utf-8')                       #encode with utf-8

But why? You just decoded it from UTF8, why are you encoding it back? You can just as well do:

 foo = self.request.get('foo')

That's equivalent to the above two lines.

To lessen your confusion on Unicode, read this: http://www.joelonsoftware.com/articles/Unicode.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文