Flask:UnicodeDecodeError:‘utf-8’编解码器无法解码位置0的字节0xff:无效的起始字节
我正在做一个使用flask模块的python项目。这不是我第一次用它,但我还是个新手。在设置一个非常简单的文件时,出现了这个错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte。
这是我的app.py文件:
from flask import Flask,render_template
app = Flask(__name__, template_folder='templates')
@app.route("/")
def index():
return render_template("index.html")
if __name__ == '__main__':
app.run(host="0.0.0.0", debug=True)
这是我的index.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask app</title>
</head>
<body>
<h1>Hello world</h1>
</body>
</html>
这个问题只在我尝试渲染模板的时候出现。如果我把渲染模板的代码去掉,换成像return "Hello world"
这样的代码,就没有问题了,去网站上我能看到“Hello world”。
这个错误的原因是什么呢?我的python版本是3.10,我是在一台linux电脑上。
我尝试在我的windows电脑上用python 3.9.13重新做这个代码,没有问题,而在我的linux电脑上用python 3.10却一直遇到这个错误。
1 个回答
0
我觉得这个问题可能是因为你在编辑HTML时使用的编码方式不对。试着运行这段代码,然后再运行app.py:
f1 = open("templates/index.html","r").read()
open("templates/index.html","wb").write(f1.encode("utf-8"))
希望这样能解决问题!