首页 > 解决方案 > 在 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 的编码,但我仍然是初学者,不知道如何更改它......我将不胜感激:)

标签: pythonhtmlflaskasciijinja2

解决方案


推荐阅读