Django:处理非ASCII参数

2 投票
2 回答
2983 浏览
提问于 2025-04-16 13:59

我在处理非ASCII字符的POST参数时遇到了问题。这里有一个CURL请求,展示了这个问题:

curl "http://localhost:8000/api/txt/" -d \
"sender=joe&comments=Bus%20%A3963.33%20London%20to%20Sydney"

comments中出现的井号(#)导致了这个问题:当我尝试对request.POST['comments']做任何操作时,我得到了:

UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 4: ordinal not in range(128)

比如说,如果我只是想记录一下comments的内容:

message = request.POST.get('comments', None)
file('/tmp/comments.txt', 'wb').write(message)

我就会收到上面的错误。或者当我尝试解码它时,我也会得到同样的错误:

try:
    message = message.decode('ISO-8859-2','ignore').encode('utf-8','ignore')
except Exception, e:
    file('/tmp/ERROR-decode.txt','w').write(str(e))

这会生成一个ERROR-decode.txt文件,内容是:

'ascii' codec can't encode character u'\ufffd' in position 4: ordinal not in range(128)

有什么想法吗?

2 个回答

0

我觉得你首先需要用urllib.unquote()来处理一下,这样可以去掉HTTP加的那些引号。然后,你就可以用合适的编码把这个字符串转换成unicode格式。

>>> unicode(urllib.unquote("Bus%20%A3963.33%20London%20to%20Sydney"), \
            "iso-8859-2").encode("utf-8") 
'Bus \xc5\x81963.33 London to Sydney'
2

%A3 是错误的。实际上应该是 %C2%A3 或者 %C5%81,这样才符合正确的UTF-8编码。

另外,可以参考一下这个链接:“Python中的Unicode,完全解密”

撰写回答