繁体   English   中英

Google App Engine上Python中的Unicode

[英]Unicode in Python on Google App Engine

我需要发出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)

但是,我一直在日志中收到此错误:

TypeError:不支持解码Unicode

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

尝试以下方法:

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

好一些评论:

 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM