1. 程式人生 > >Python中urllib.urlencode中文字符的一個問題

Python中urllib.urlencode中文字符的一個問題

如果 ice pytho div win enc nbsp window gbk

Django項目在訪問Restful service時調用urllib.urlencode編碼中文字符串時碰到下面這個錯誤、

v = quote_plus(str(v))  
UnicodeEncodeError: ascii codec cant encode characters in position...........

這個錯誤在windows7的開發環境下沒有發生,在Linux生產環境下發生了,比較郁悶,剛上線以後的Bug.Google以後,在一份中文資料(鏈接見參考資料)中看到URL字符串不能是Unicode字符串,如果時,得編碼成GBK或者UTF-8,在Django環境中,這個的確比較討厭,所幸及時發現這個資料,對那段中文字符串采用了encode(‘utf-8‘)的方法做了編碼轉換:

utfstr =  unicodeStr.encode(utf-8)  

把那個utfstr傳給相應的url編碼函數即可。

參考資料:http://lijiang.iteye.com/blog/312247

Python中urllib.urlencode中文字符的一個問題