Flask:在模板中渲染unicode字符

时间:2014-07-04 04:03:36

标签: python unicode flask

在我正在处理的Flask应用中,我需要向用户显示Unicode文本。在Python shell中测试它们时,我的函数似乎工作正常:

>>> sr = rym_scraper.get_artist_info('sigur ros')
>>> print sr.name # a string encoded using str.encode('utf8')
Sigur Rós

当我在应用程序中实际测试时,我得到了这个:

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

最后一个异常在模板中,它产生了这个堆栈跟踪:

Traceback (most recent call last):
  File "/Users/eric/Envs/whatshouldilistento/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/eric/Envs/whatshouldilistento/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Users/eric/Envs/whatshouldilistento/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/eric/Envs/whatshouldilistento/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/eric/Envs/whatshouldilistento/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/eric/Envs/whatshouldilistento/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/eric/projects/whatshouldilistento/app/app.py", line 29, in enter_band
    return band_info(form.name.data)
  File "/Users/eric/projects/whatshouldilistento/app/app.py", line 45, in band_info
    return render_template('band_info.html')
  File "/Users/eric/Envs/whatshouldilistento/lib/python2.7/site-packages/flask/templating.py", line 125, in render_template
    context, ctx.app)
  File "/Users/eric/Envs/whatshouldilistento/lib/python2.7/site-packages/flask/templating.py", line 107, in _render
    rv = template.render(context)
  File "/Users/eric/Envs/whatshouldilistento/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render
    return self.environment.handle_exception(exc_info, True)
  File "/Users/eric/Envs/whatshouldilistento/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/eric/projects/whatshouldilistento/app/templates/band_info.html", line 9, in top-level template code
    <div>{{ message }}</div>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3: ordinal not in range(128)

如何在渲染模板中显示Unicode字符串?

3 个答案:

答案 0 :(得分:7)

将以下内容添加到您的启动文件中

import sys
if sys.version_info.major < 3:
    reload(sys)
sys.setdefaultencoding('utf8')

这对我有用

答案 1 :(得分:6)

您的邮件不是ascii,您必须对其进行解码并将其转换为unicode

你可以使用它来转换它。

{{ message.decode('utf-8') }}

答案 2 :(得分:0)

我的unicode字符串嵌入在数组和对象中,我使用json.dumps()传递它们以消除unicode引用。

https://stackoverflow.com/a/50612950/999943