在HTML中显示异常字符

时间:2016-12-17 21:01:18

标签: python html

我从我的数据库中提取了以下字符串:

“赖特突然陷入了一种远离平凡的生活,一旦他适应了它,就会出奇的好......”

这正是在控制台上打印出来的文本。请注意,三点是单个字符。

现在,当我通过模板将此数据传递给HTML时,我收到以下错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 383: ordinal not in range(128)

知道怎么解决这个问题吗?我是否需要以某种方式编码为UTF-8。我在我的后端使用python。

修改

后端代码是:

print "INFO: ", data[2]

return render_template('index.html', title=data[1], info=data[2].encode("utf-8"), backdrop=data[4], imdbrat=data[7], rtrat=data[9], cert=data[10], yt=data[11], runtime=data[12]);

在模板(index.html)中我有:

<p> {{info}} </p>

输出结果为:

INFO:  The life of Danny Wright, a salesman forever on the road, veers into dangerous and surreal territory when he wanders into a Mexican bar and meets a mysterious stranger, Julian, who's very likely a hit man. Their meeting sets off a chain of events that will change their lives forever, as Wright is suddenly thrust into a far-from-mundane existence that he takes to surprisingly well … once he gets acclimated to it.
[2016-12-17 21:06:14,846] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/dennis/moviechoosy/moviechoosy/app.py", line 31, in home
    return render_template('index.html', title=data[1], info=data[2].encode("utf-8"), backdrop=data[4], imdbrat=data[7], rtrat=data[9], cert=data[10], yt=data[11], runtime=data[12]);
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 383: ordinal not in range(128)

1 个答案:

答案 0 :(得分:0)

'...'字符是水平省略号。

>>> import unicodedata
>>> c = unicodedata.lookup('HORIZONTAL ELLIPSIS')
>>> c
u'\u2026'
>>> print c
…

编码为utf-8,它以0xe2:

开头
>>> b = c.encode('utf-8')
>>> b
'\xe2\x80\xa6'

Flask docs表示模板的非ascii字符串在传递给render_template时应解码为unicode。

  

如果在字符串中需要除ASCII以外的任何内容,则必须标记此内容   字符串作为Unicode字符串,前缀为小写u。 (喜欢   u'HänselundGretel')

因此,您的数据库中似乎有一个Python2字符串,编码为u​​tf-8。所以你需要解码到unicode

>>> u = b.decode('utf-8')

然后Flask / Jinja2应该正确处理它。