python 中的 jinja2 编码错误

jinja2 encoding error in python

所以我正在尝试将 jinja2 用于一个简单的 html 模板,但是当我调用 render() 时我一直收到此错误:

Warning: IronPythonEvaluator.EvaluateIronPythonScript operation failed. 
Traceback (most recent call last):
File "C:\Program Files (x86)\IronPython 2.7\Lib\jinja2\jinja2\loaders.py", line 125, in load
File "C:\Program Files (x86)\IronPython 2.7\Lib\jinja2\jinja2\environment.py", line 551, in compile
File "C:\Program Files (x86)\IronPython 2.7\Lib\jinja2\jinja2\environment.py", line 470, in _parse
File "C:\Program Files (x86)\IronPython 2.7\Lib\jinja2\jinja2\parser.py", line 31, in __init__
File "C:\Program Files (x86)\IronPython 2.7\Lib\jinja2\jinja2\environment.py", line 501, in _tokenize
File "C:\Program Files (x86)\IronPython 2.7\Lib\jinja2\jinja2\environment.py", line 494, in preprocess
File "<string>", line 21, in <module>
File "C:\Program Files (x86)\IronPython 2.7\Lib\jinja2\jinja2\environment.py", line 812, in get_template
File "C:\Program Files (x86)\IronPython 2.7\Lib\jinja2\jinja2\environment.py", line 786, in _load_template
UnicodeEncodeError: ('unknown', '\x00', 0, 1, '')

现在我知道 jinja2 只能与 utf-8 一起使用,所以我强制我的 python 代码采用该格式:

#-*- coding: utf-8 -*-

import clr
import sys

pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib'
sys.path.append(pyt_path)

pyt_path1 = r'C:\Program Files (x86)\IronPython 2.7\Lib\MarkupSafe'
sys.path.append(pyt_path1)

pyt_path2 = r'C:\Program Files (x86)\IronPython 2.7\Lib\jinja2'
sys.path.append(pyt_path2)

#The inputs to this node will be stored as a list in the IN variable.
dataEnteringNode = IN

from jinja2 import Environment, FileSystemLoader

j2_env = Environment(loader=FileSystemLoader(r'C:\Users\ksobon\Documents\Visual Studio 2015\Projects\WebSite2'), trim_blocks=True)
temp = j2_env.get_template('HTMLPage2.html')

OUT = temp.render(svgWidth = r'500')

这是我尝试使用的模板 html 文件:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
    .chart rect {
      fill: steelblue;
      stroke: white;
    }
</style>
<svg class="chart"></svg>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var data = [
  { name: "Locke", value: 42 },
  { name: "Reyes", value: 8 },
  { name: "Ford", value: 15 },
  { name: "Jarrah", value: 16 },
  { name: "Shephard", value: 23 },
  { name: "Kwon", value: 42 }
];

var w = {{svgWidth}},
    h = 400;

var x = d3.scale.linear()
    .domain([0, 1])
    .range([0, w]);

var y = d3.scale.linear()
    .domain([0, 100])
     .rangeRound([0, h]);

var chart = d3.select("body")
.append("svg:svg")
.attr("class", "chart")
.attr("width", w * data.length - 1)
.attr("height", h);

chart.selectAll("rect")
.data(data)
.enter().append("svg:rect")
.attr("x", function (d, i) { return x(i) - .5; })
.attr("y", function (d) { return h - y(d.value) - .5; })
.attr("width", w)
.attr("height", function (d) { return y(d.value); });

</script>

知道我做错了什么吗?我在 IronPython2.7

编辑:

UnicodeEncodeError: ('unknown', '\x00', 0, 1, '')

嗯...这似乎与 this question 中的错误相同,模板加载器中的一些错误?


原回答:

Now I understand that jinja2 only works with utf-8 so I am forcing my python code to that formatting:

# -*- coding: utf-8 -*-

上面的行只是告诉 Python 源代码文件是使用 utf-8 编码的,因此它知道如何解释字符串文字。

然而,这并不意味着发送到 Jinja 的字符串是 unicode 实例,这是 Jinja 所期望的。来自 docs:

Jinja2 is using Unicode internally which means that you have to pass Unicode objects to the render function or bytestrings that only consist of ASCII characters.

这意味着您需要将字符串转换为 unicode 个实例。对于字符串文字,您可以在它们前面加上 u:

text = u'This string literal is a unicode instance'

对于只是计划字节序列的字符串变量,您需要先对它们进行解码,这包括您加载的HTML模板:

>>> value = 'foö'
>>> type(value)
<type 'str'>
>>> unicode_value = value.decode('utf8')
>>> type(unicode_value)
<type 'unicode'>
>>> print unicode_value
foö

这是 IronPython 中的 known bug。您可以通过编辑 Jinja2 源来解决它:

Using Jinja2 on IronPython with non-ASCII characters in a template will result in this error. Replace to_string = unicode with to_string = lambda x: unicode(x) near the top of runtime.py to work around this issue.

在 jinja2 2.8 中,不要修改 runtime.py,因为它在接受的答案中说了。相反,将文件 _compat.py text_type = unicode 的第 52 行替换为

text_type = lambda x: unicode(x)