我遇到了處理非ascii POST參數的問題。下面是顯示問題的捲曲要求:Django:處理非ascii參數
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)
想法?
對不起Stefano,我沒有說清楚它是在Django的背景下; django已經爲你引用了POST參數,所以'comments'是一個沒有引號的字符串。 – Parand 2011-03-18 20:53:36
@Parand:好的。很公平。那麼您收到的是必須通過正確的編碼轉換爲unicode的字符串。我使用'unicode(str,「encoding」)'這是明確的意圖。然後,如果你願意的話,你可以'編碼()'這個unicode對象爲utf-8。 – 2011-03-18 20:55:23
不,接收的是一個字符串,它已經被錯誤地轉換爲「unicode」,因此存在U + FFFD。 – 2011-03-18 20:57:06