我在python中使用jinja2模板语言来显示一个网站。python解码/编码地狱(使用jinja2)
相关的源代码如下所示:
# -*- coding: utf-8 -*-
...
template_values = {'name': u'abwärtz'}
template = jinja_environment.get_template('Home.html')
print(template.render(template_values))
...
有趣的是,如果我使用:
template_values = {'name': u'abw_rtz'}
一切工作只是完美!
...对于Jinja2的模板的默认编码被认为是 UTF-8。
...要明确使用Unicode字符串,您必须在字符串前加字母“0:u'Hänselund Gretel sagen Hallo”。这样,Python 将通过对来自当前Python模块的 字符编码的字符串进行解码来将该字符串存储为Unicode。如果没有编码 指定此默认为“ASCII”这意味着你不能使用任何非 ASCII标识符....
所以,只要使用u'äöü”,一切都应该工作,对不对?
这就是我得到:
template_values = {'name': unicode('abwärtz','utf-8') }
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe4 in position 3: invalid continuation byte
template_values = {'name': u'abwärtz' }
SyntaxError: (unicode error) 'utf8' codec can't decode byte 0xe4 in position 0: unexpected end of data
template_values = {'name': unicode('abwärtz',"ISO-8859-1") }
--> everything works just perfect!
我在Windows 7和sys.getdefaultencoding()
回报ASCII工作。
有人可以解释这种奇怪的行为吗? 我正在寻找一个解决方案,其中'名称':也处理中文或西里尔文字符。
你用什么编辑器编写代码?假设我的回答是正确的,有人可能会告诉你如何正确配置几乎所有的编辑器,除了记事本(如果你是记事本,答案是停止这样做)。 – abarnert 2014-09-25 23:26:40
我正在使用Notepad ++ – user1911091 2014-09-26 07:57:06