在html烧瓶中打印时出现unicode错误

时间:2015-07-08 09:23:38

标签: unicode flask

在html Flask中打印时出现unnicode错误。 这是我的代码。

{% if(backpaths) %}
{%   for n in backpaths:%}
{%      print '%s'%n %}
</br>
{%   endfor %}
{% endif %}

我尝试使用n.decode('utf-8'),但它无法正常运行并出现同样的错误

backpaths设置为:

['1\xe6\x9c\x89 --(HYPER)--> quantifier={indefinite|\xe4\xb8\x8d\xe5\xae\x9a\xe6\x8c\x87} --(HYPO)--> \xe6\x9c\x89 ', '2\xe6\x9c\x89 --(HYPER)--> exist|\xe5\xad\x98\xe5\x9c\xa8 --(HYPO)--> \xe6\x9c\x89 ']

这里是追溯

(most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/ganchimeg/FlaskApp/FlaskApp/__init__.py", line 125, in homepage
    return render_template('index.html', backpaths=successPaths)
  File "/usr/local/lib/python2.7/dist-packages/flask/templating.py", line 128, in render_template
    context, ctx.app)
  File "/usr/local/lib/python2.7/dist-packages/flask/templating.py", line 110, in _render
    rv = template.render(context)
  File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 969, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 742, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/ganchimeg/FlaskApp/FlaskApp/templates/index.html", line 31, in top-level template code
    {{      n }}
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 16: ordinal not in range(128)

1 个答案:

答案 0 :(得分:0)

您没有Unicode字符串,您有字节字符串。 Python尝试使用标准ASCII编解码器隐式解码那些。明确解码它们:

{% if(backpaths) %}
{%   for n in backpaths:%}
{{       n.decode('utf8') }}
</br>
{%   endfor %}
{% endif %}

如果您将backpaths传入准备解码的模板,那会更好。