部署FastAPI到Heroku时无法找到templates目录下的HTML文件
解决Heroku部署后Jinja2 TemplateNotFound问题
部署到Heroku后出现jinja2.exceptions.TemplateNotFound错误,本地正常但云端报错,大概率是文件追踪、路径大小写或路径验证的问题,以下是针对性解决步骤:
确认Git已追踪所有模板文件
Heroku通过Git仓库同步代码,如果templates目录下的文件没被添加到Git,部署后云端就没有这些文件。执行以下命令:git add templates/ git commit -m "Add all template files" git push heroku main(如果你的部署分支不是
main,替换为对应的分支名称)检查文件名大小写
Windows系统大小写不敏感,但Heroku运行在Linux环境下,文件名严格区分大小写。比如代码里引用home.html,但实际文件是Home.html,本地能正常加载,但云端会找不到。确保代码中模板名称和实际文件名的大小写完全一致。添加日志验证路径正确性
修改代码添加日志输出,确认BASE_DIR和模板目录的实际路径:import os # 根据你使用的框架导入Jinja2Templates,比如FastAPI from fastapi.templating import Jinja2Templates BASE_DIR = os.path.realpath(os.path.dirname(__file__)) print(f"Current BASE_DIR: {BASE_DIR}") print(f"Template directory exists: {os.path.exists(os.path.join(BASE_DIR, 'templates'))}") print(f"Home.html exists: {os.path.exists(os.path.join(BASE_DIR, 'templates', 'home.html'))}") templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates"))部署后用Heroku CLI查看实时日志:
heroku logs --tail从日志中确认模板目录和目标文件是否存在,如果不存在,说明路径计算有误或者文件没被正确部署。
确认模板渲染代码的正确性
检查渲染模板的代码,确保传入的模板名称正确,比如:@app.get("/") async def root(request: Request): return templates.TemplateResponse("home.html", {"request": request})这里的
"home.html"必须和templates目录下的文件名完全一致。
内容的提问来源于stack exchange,提问作者Tom Jeremiah
相关产品推荐
相关产品推荐

