【发布时间】:2017-05-03 08:24:00
【问题描述】:
我从我的数据库中提取了以下字符串:
“Wright 突然被推入了一个远离世俗的生活,他对这种生活出奇地好……一旦他适应了它。”
这正是控制台上打印的文本。请注意,三点是单个字符。
现在,当我通过模板将此数据传递到 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)
【问题讨论】:
-
"带有奇怪字符的字符串".encode('utf-8') ?
-
这似乎没有任何区别
-
您仍然收到错误消息吗?你能发布你的代码吗?我有一个类似的问题,我的回答解决了它,但你可能需要在其他地方转换它。
标签: python html python-2.7 character-encoding jinja2