Flask部署到Heroku后出现jinja2 TemplateNotFound错误如何解决
问题描述
我在阅读相关问题后,对部署到Heroku后启动应用时出现的如下报错原因有了初步了解:raise TemplateNotFound(template), jinja2.exceptions.TemplateNotFound: index.html
现有资料指出templates目录需要放在项目根目录下。我因项目体量变大、结构逐渐杂乱调整了项目结构,请问能否修改Heroku查找templates目录的路径?
我的当前项目结构如下:
Project │ ├── App │ ├── DbMs │ │ ├── db_actions.py │ │ └── user_operations.py │ ├── UI │ │ ├── static │ │ │ ├── css │ │ │ │ └── main.css │ │ │ ├── fonts │ │ │ │ └── Gotham_Medium_Regular.json │ │ │ ├── images │ │ │ │ ├── favicons │ │ │ │ │ ├── android-chrome-192x192.png │ │ │ │ │ ├── android-chrome-512x512.png │ │ │ │ │ ├── apple-touch-icon.png │ │ │ │ │ ├── favicon-16x16.png │ │ │ │ │ ├── favicon-32x32.png │ │ │ │ │ ├── favicon.ico │ │ │ │ │ └── site.webmanifest │ │ │ │ ├── header.jpeg │ │ │ │ ├── logo.png │ │ │ │ └── radar-chart.png │ │ │ └── javascript │ │ │ ├── FontLoader.js │ │ │ ├── TextGeometry.js │ │ │ ├── create.js │ │ │ ├── exploreMusic.js │ │ │ └── tracks.js │ │ └── templates │ │ ├── base.html │ │ ├── create.html │ │ ├── index.html │ │ ├── information.html │ │ └── tracks.html │ ├── __init__.py │ ├── authenticate.py │ ├── routes.py │ ├── services.py │ └── templates ├── Pipfile ├── Procfile ├── README.md ├── Testing │ ├── __init__.py │ └── testing.py ├── __pycache__ │ ├── authenticate.cpython-39.pyc │ ├── config.cpython-39.pyc │ ├── main.cpython-39.pyc │ ├── services.cpython-39.pyc │ └── user_operations.cpython-39.pyc ├── config.py ├── package-lock.json ├── package.json ├── requirements.txt ├── run.py └── setup.py
补充说明:该应用在本地运行完全正常,仅部署后会出现上述错误。
编辑补充:我已经尝试将templates文件夹移动到App目录以及项目根目录,两次操作都同步修改了__init__.py中的对应配置行:
template_dir = os.path.abspath('../Project/templates/')
每次修改模板位置后都重新部署,Heroku仍然返回相同报错:raise TemplateNotFound(template) jinja2.exceptions.TemplateNotFound: index.html
解决方案
你遇到的问题本质是硬编码的相对路径和Heroku运行环境的工作目录结构不匹配,本地路径规则在Heroku的容器环境中不生效,按以下步骤操作即可解决:
- 首先删除冗余目录:删掉
App目录下和UI文件夹同级的空templates目录,避免路径匹配冲突。 - 修改Flask实例初始化的路径配置,改用基于当前文件的动态路径计算,不要用跳转到上级目录的硬编码相对路径。如果你的Flask实例定义在
App/__init__.py中,示例写法如下:
import os from flask import Flask # 基于当前文件的绝对路径动态计算模板、静态文件目录位置 current_file_dir = os.path.dirname(os.path.abspath(__file__)) template_dir = os.path.join(current_file_dir, 'UI', 'templates') static_dir = os.path.join(current_file_dir, 'UI', 'static') # 初始化Flask实例时显式指定路径 app = Flask(__name__, template_folder=template_dir, static_folder=static_dir)
- 检查Procfile的启动命令是否和本地运行的入口一致,比如用gunicorn启动时,Procfile内容应为
web: gunicorn run:app(具体入口根据你自己的启动文件调整即可)。 - 提交所有修改重新部署即可正常运行。
内容的提问来源于stack exchange,提问作者wisenickel
相关产品推荐
相关产品推荐

