python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python访问报错:jinja2.exceptions.TemplateNotFound:index.html

解决python访问报错:jinja2.exceptions.TemplateNotFound:index.html

作者:三省同学

这篇文章主要介绍了解决python访问报错:jinja2.exceptions.TemplateNotFound:index.html,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

背景

项目目录结构

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 # 存储访问数据文件

重启后,成功访问。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文