作者doomleika (iSuck)
看板Python
標題[問題] Python 2.7與UTF-8
時間Wed Jul 31 01:45:19 2013
前陣子寫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
→ birdhackor:python 2 的內部預設編碼不是 utf8 而 python 3 是 07/31 15:10
→ birdhackor:python 3 的 str 對應 python 2 的 unicode 07/31 15:11
→ birdhackor:python 3 的 bytes 對應 python 2 的 str 07/31 15:11
→ birdhackor:因為這些不同 django 用到的 __str__ 等方法在 07/31 15:13
→ birdhackor:py2k 與 py3k 應該對應不同的方法才對 07/31 15:13
→ birdhackor:所以才使用這個修飾器來針對不同版本做修正 07/31 15:14
→ doomleika:我有點似懂非懂<_<不過謝謝你的回應 07/31 18:07
→ doomleika:感覺有點頭緒了 07/31 18:07
→ sbrhsieh:主要的癥結在於 pre py3,string 有兩種:str, unicode 07/31 20:06
→ sbrhsieh:而多數的人並不單純把3.0-的str當byte sequence用而已 07/31 20:08