背景
项目目录结构
test/
–index.html # 主页
–app.py
–count.json # 存储访问数据文件
三个文件均在同一级。
文件内容
app.py
from flask import Flask
from flask import render_template
from json import load, dump
app = Flask(__name__)
app.config["SECRET_KEY"] = '123456'
@app.route("/")
def index():
with open("count.json") as f:
# 读取计数文件并+1回写
people = load(f) + 1
with open("count.json", "w") as f:
dump(people, f)
return render_template("index.html", people=str(people))
if __name__ == "__main__":
app.run(host="127.0.0.1", port="8000", debug=True)
count.josn
0
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>网站首页</h1>
<p>Hello World! 该页面已被访问<b>{{ count }}</b>次。</p>
</body>
</html>
运行报错:
jinja2.exceptions.TemplateNotFound
jinja2.exceptions.TemplateNotFound: index.html
Traceback (most recent call last)
解决
render_template方法会在同级templates目录下查找。
调整index.html文件位置解决。
调整后目录结构:
test/
--templates/
index.html # 主页
--app.py
--count.json # 存储访问数据文件
重启后,成功访问。
点赞 收藏 关注