1

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

4

2 回答 2

7

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

试试这个:

if isinstance(var, str):
    var = unicode(var, 'utf-8')
else:
    var = unicode(var)
于 2010-12-22T13:35:41.293 回答
1

好的一些评论:

 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

于 2010-12-22T14:37:00.247 回答