python - 在 html 模板中使用 Jinja2 时出错:[UnicodeDecodeError]
问题描述
所以我有一个 html 模板,其中包含一些基本的 jinja 表达式,例如:
{{ post.content }}
我的 html 和 python 文件的编码是 utf-8。所以这个 jinja 表达式正在加载一个简单的 json,它是我在一个名为 db 的 python 文件中创建的,就像这样:
post = [{"content" : "Rémi"}]
举个例子..问题是当用 渲染html模板时post.content=db.post
,我得到这个错误:
奇怪的是几天前我没有收到这个错误。
Traceback (most recent call last):
File "/Library/Python/3.7/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/3.7/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/Library/Python/3.7/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/3.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Python/3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Python/3.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/routes.py", line 55, in feed
return render_template('feed.html', posts=db.posts)
File "/Library/Python/3.7/site-packages/flask/templating.py", line 135, in render_template
context, ctx.app)
File "/Library/Python/3.7/site-packages/flask/templating.py", line 117, in _render
rv = template.render(context)
File "/Library/Python/3.7/site-packages/jinja2/environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "/Library/Python/3.7/site-packages/jinja2/environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "/feed.html", line 56, in top-level template code
<p id="content">{{ post.content }}</p>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)
我认为问题在于 json 的编码,但我仍然是初学者,不知道如何更改它......我将不胜感激:)
解决方案
推荐阅读
- java - 根据哪个过滤器过滤了流中的最后一个元素,做出不同的反应
- javascript - 如何在不使用formdata api的情况下使用axios上传文件?
- mysql - MySQL:为所有用户将数据从一个表中的字段移动到另一表中的字段
- php - 单击类别名称时,页面将重定向到 404 pge
- django - 如何将两个日期更改为天数和小时数
- javascript - React Storybook - 自定义道具导致“您可能需要适当的加载器来处理此文件类型”消息
- css - CSS网格:自动适应垂直跨度
- svelte - Svelte TypeError 无法解构 getContext(...) 的属性,因为它未定义
- java - Android TV 应用开发 - 使用 Kotlin/Java 更改系统设置
- python - -215:opencv 程序中的断言失败