2009-07-16 41 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)

相关问题