Flask:在temp中呈现unicode字符

2024-06-16 08:27:57 发布

您现在位置:Python中文网/ 问答频道 /正文

在我正在开发的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字符串?


Tags: inpyselfinfoappflasklibpackages
3条回答

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

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

这对我有用

您的消息是非ascii的,您必须对其进行解码并将其转换为unicode

您可以使用转换它。

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

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

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

相关问题 更多 >