首页 > 解决方案 > Unicode 错误烧瓶 jinja2

问题描述

我希望在烧瓶上创建一个带有 python 的网页,一切都很好,我会大力推荐烧瓶。但是当涉及到 Unicode et 编码时,它总是在 python 网页等之间很难。

所以我有一个表格,我在特定的烧瓶路线上发布,我得到了我的值,我需要做一些小包装来让我的变量井井有条。

我得到了这个字典:

            task_formatted.append(str(item['entity']))

我将它转换为一个 str 然后我将它附加到一个列表中,这样我就可以轻松地将它传递给我的模板

我希望 str 在网页 python 页面上呈现为 UTF-8:

  # -*- coding: utf-8 -*- 

html页面:

  <meta charset="utf-8"/>

然后我使用 jinja 在我的页面中打印它们:

            {% for item in task %}
            <tr>
              <td>{{item[0].decode('utf-8')}}</td>
              <td>{{item[1].decode('utf-8')}}</td>
              <td>{{item[2]}}</td>
              <td>{{item[3]}}</td>
              <td>{{item[4]}}</td>
              <td><button id="taskmodal1"></td>
            </tr>
            {% endfor %}

但我的 item[0].decode('utf-8') 和我的 item[1].decode('utf-8')

正在打印:

{'type': 'Asset', 'id': 1404, 'name': 'Test-Asset comm\xc3\xa9'}

代替

{'type': 'Asset', 'id': 1404, 'name': 'Test-Asset commé'}

我已经尝试了几种使用 .encode('utf-8') 在 python 端使用 unicode(str) 和 render_template().encode('utf-8') 的方法而且我越来越没有想法了。

公平地说,我认为它们是我对 Unicode 不理解的东西,所以我想得到一些解释(不是文档链接,因为我很可能已经阅读过它们)或一些解决方案来让它工作,

对于我的程序能够正确编写 str 非常重要,我在 js http 调用之后使用它。

谢谢

PS:我正在使用python2

标签: pythonflaskunicodejinja2repr

解决方案


我得到了这个字典:

task_formatted.append(str(item['entity']))

我将其转换为 a str,然后将其附加到列表中,以便我可以轻松地将其传递给我的模板

这段代码没有做你认为它做的事情。

>>> entity = {'type': 'Asset', 'id': 1404, 'name': 'Test-Asset commé'}
>>> str(entity)
"{'type': 'Asset', 'id': 1404, 'name': 'Test-Asset comm\\xc3\\xa9'}"

当您调用str字典(或列表)时,您不会得到调用str字典的每个键和值的结果:您会得到每个键和值的repr。在这种情况下,这意味着“Test-Asset commé”已以难以逆转的方式转换为“Test-Asset comm\xc3\xa9”。

>>> str(entity).decode('utf-8')  # <- this doesn't work.
u"{'type': 'Asset', 'id': 1404, 'name': 'Test-Asset comm\\xc3\\xa9'}"

如果你想在模板中渲染你的字典,{{ item }}你可以使用 json 模块来序列化它们,而不是str. 请注意,您需要将 json (类型为str)转换为unicode实例以避免UnicodeDecodeError在呈现模板时出现。

>>> import json
>>> template = jinja2.Template(u"""<td>{{item}}</td>""")
>>> j = json.dumps(d, ensure_ascii=False)
>>> uj = unicode(j, 'utf-8')
>>> print template.render(item=uj)
<td>{"type": "Asset", "id": 1404, "name": "Test-Asset commé"}</td>

一些一般性意见/要点:

  • 不要使用str(or unicode) 来序列化字典或列表等容器;使用jsonpickle 之类的工具。
  • 确保您传递给 jinja2 的任何字符串文字都是 的实例unicode,而不是str
  • 使用 Python2 时,如果您的代码有可能处理非 ascii 值,请始终使用unicode,永远不要使用str

推荐阅读