2009-07-16 40 views
2

當試圖渲染Django模板文件中的谷歌應用程序引擎谷歌應用程序引擎模板的Unicode解碼問題

from google.appengine.ext.webapp import template

templatepath = os.path.join(os.path.dirname(file), 'template.html')
self.response.out.write (template.render(templatepath , template_values))

我遇到了以下錯誤:

<type 'exceptions.UnicodeDecodeError'>: 'ascii' codec can't decode byte 0xe2 in position 17692: ordinal not in range(128)
args = ('ascii', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Str...07/a-beautiful-method-to-find-peace-of-mind/ -->
', 17692, 17693, 'ordinal not in range(128)')
encoding = 'ascii'
end = 17693
message = ''
object = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Str...07/a-beautiful-method-to-find-peace-of-mind/ -->
reason = 'ordinal not in range(128)'
start = 17692

看來,基本的Django模板引擎採用了「ascii」編碼,應該是「utf-8」。 任何人都知道可能會導致麻煩以及如何解決它? 謝謝。

+1

DEFAULT_CHARSET的值是多少? 可能會有所幫助。 – lavinio 2009-07-16 18:00:46

回答

6

嘛,原來由模板返回渲染的結果需要被首先解碼:

self.response.out.write (template.render(templatepath , template_values).decode('utf-8'))

一個愚蠢的錯誤,但噸反正每個人都有答案。 :)

1

你檢查了你的文本編輯器,該模板是用utf-8編碼的嗎?

2

你使用的是Django 0.96還是Django 1.0?您可以通過查看您的main.py,看到檢查它是否包含以下內容:

 
from google.appengine.dist import use_library 
use_library('django', '1.0')

如果你使用Django 1.0,兩者FILE_CHARSET和DEFAULT_CHARSET應該默認爲「UTF-8」。如果您的模板以不同的編碼保存,只需將FILE_CHARSET設置爲任何內容即可。

如果您使用Django 0.96,您可能想嘗試直接從磁盤讀取模板,然後手動處理編碼。

例如,更換

template.render(templatepath , template_values)

Template(unicode(template_fh.read(), 'utf-8')).render(template_values)

相關問題