python - 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
解决方案
我得到了这个字典:
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>
一些一般性意见/要点:
推荐阅读
- c# - 将用户上传的图片保存到 Google Cloud
- dax - 在 DAX 查询中按年份过滤 - 表格多维数据集
- angular - 在 Angular 中,是否可以在 patchValue 中验证 required ?
- html - Chrome 自动完成功能认为我的“名字”字段是信用卡
- python - Python ThreadPoolExecutor 线程未完成
- javascript - 如何从 API 响应中获取初始 Redux 状态?
- google-chrome-extension - 如何在 Google Chrome 开发者仪表板中为扩展设置价格?
- python - 在 Keras 中使用自定义顶层为 vgg16 生成热图
- ms-access - 访问 - 在一张图上绘制两个时间序列
- python - 为什么变量不会在打印行中相乘