解决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 # 存储访问数据文件
重启后,成功访问。

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Python处理JSON的完全指南:从基础到实战,掌握数据交换核心技能
本文将从 JSON 与 Python 的类型映射讲起,带你理解序列化与反序列化的底层逻辑,然后通过实战案例演示如何解析 API 数据、处理自定义对象,最后总结出 3 个避坑技巧2026-06-06
编写Python脚本把sqlAlchemy对象转换成dict的教程
这篇文章主要介绍了编写Python脚本把sqlAlchemy对象转换成dict的教程,主要是基于Python的model类构建一个转换的方法,需要的朋友可以参考下2015-05-05
Django中针对基于类的视图添加csrf_exempt实例代码
这篇文章主要介绍了Django中针对基于类的视图添加csrf_exempt实例代码,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下2018-02-02


最新评论