[問題] Python 2.7與UTF-8

看板Python作者 (iSuck)時間12年前 (2013/07/30 17:45), 編輯推噓0(0010)
留言10則, 3人參與, 最新討論串1/2 (看更多)
前陣子寫django東西的時候遇到了一點問題: 'ascii' codec can't encode characters in position 0-11: ordinal not in range(128) ... Unicode error hint The string that could not be encoded/decoded was: 登入失敗,請修正帳號密碼 Error during template rendering 這個問題在開發的OS(windows 7)上不會發生,但是到了deploy(ubuntu 12.04)的機器上就 會出錯,找了半天才知道我override裡面一個class的時候忘了加decorator 「python_2_unicode_compatible」(http://0rz.tw/jAQkg),他的說明與原始碼如下: 說明: A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. 原始碼: def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if not six.PY3: klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass 似乎Python 2.7裡面對於UTF-8的支援上有一些奇奇怪怪的眉角,不知道版上的朋友可以 給點說明或是解答的方向或是關鍵字?謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 42.79.167.203

07/31 15:10, , 1F
python 2 的內部預設編碼不是 utf8 而 python 3 是
07/31 15:10, 1F

07/31 15:11, , 2F
python 3 的 str 對應 python 2 的 unicode
07/31 15:11, 2F

07/31 15:11, , 3F
python 3 的 bytes 對應 python 2 的 str
07/31 15:11, 3F

07/31 15:13, , 4F
因為這些不同 django 用到的 __str__ 等方法在
07/31 15:13, 4F

07/31 15:13, , 5F
py2k 與 py3k 應該對應不同的方法才對
07/31 15:13, 5F

07/31 15:14, , 6F
所以才使用這個修飾器來針對不同版本做修正
07/31 15:14, 6F

07/31 18:07, , 7F
我有點似懂非懂<_<不過謝謝你的回應
07/31 18:07, 7F

07/31 18:07, , 8F
感覺有點頭緒了
07/31 18:07, 8F

07/31 20:06, , 9F
主要的癥結在於 pre py3,string 有兩種:str, unicode
07/31 20:06, 9F

07/31 20:08, , 10F
而多數的人並不單純把3.0-的str當byte sequence用而已
07/31 20:08, 10F
文章代碼(AID): #1Hz_koHf (Python)
討論串 (同標題文章)
文章代碼(AID): #1Hz_koHf (Python)