[問題] Python 2.7與UTF-8
前陣子寫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
07/31 15:10, 1F
→
07/31 15:11, , 2F
07/31 15:11, 2F
→
07/31 15:11, , 3F
07/31 15:11, 3F
→
07/31 15:13, , 4F
07/31 15:13, 4F
→
07/31 15:13, , 5F
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
07/31 20:06, 9F
→
07/31 20:08, , 10F
07/31 20:08, 10F
討論串 (同標題文章)
完整討論串 (本文為第 1 之 2 篇):