【问题标题】:Python 3.8.5 Flask giving internal server error with WSGI application when template is called using render_template in VS Code - 500 server error [duplicate]在 VS Code 中使用 render_template 调用模板时,Python 3.8.5 Flask 在 WSGI 应用程序中出现内部服务器错误 - 500 服务器错误 [重复]
【发布时间】:2021-01-30 02:12:44
【问题描述】:

我一直在关注 Corey Schafer 使用 Flask 制作的 YouTube 教程。我已经到达了关于使用 html 模板的第二个教程,但这是我唯一到达的地方。这是我正在运行的名为 hello.py 的程序:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

app.run()

这是我一直在使用的 HTML 文件,名为 home.html:

<!DOCTYPE html>
<html>
  <head>
    <title>Flask Template Example</title>
</head>
<body>
    <div>
        <p>{{ message }}</p>
    </div>
</body>
</html>

每当我尝试运行我的代码时,我总是会收到错误 jinja2.exceptions.TemplateNotFound: template.html。我试图查看所有可能的解决方案,但似乎都没有奏效。我该如何解决这个问题?我在 Windows 64 位机器上。

【问题讨论】:

  • 您的home.html 文件在哪里?使用默认配置,它应该位于名为templates 的子目录中
  • 我的 home.html 文件位于 templates 子目录中。
  • 您的错误消息似乎与您发布的代码不一致。该文件似乎被称为home.html,而错误涉及template.html

标签: python flask web jinja2


【解决方案1】:

默认情况下,在 Flask 中,模板文件夹为 templates/。如果home.htmlapp.py在同一目录下,则需要设置template_folder

这里是修复你的app.py的方法:

from flask import Flask, render_template

app = Flask(__name__, template_folder='./')

@app.route('/')
def home():
    return render_template('home.html')

app.run()

要使用默认模板位置(推荐),这是您需要的文件结构:

app.py
templates
└── home.html

【讨论】:

  • 您好,我尝试将您的代码粘贴到我的编辑器中,但仍然无法正常工作。我得到了同样的错误 jinja2.exceptions.TemplateNotFound: template.html。我还检查了我的文件结构,它与你给出的结构基本一致。
  • 我还检查了我在 Libs 中的 templating.py 应用程序,发现 '.globals' 和 '.signals' 未解析。这会导致任何问题吗?
  • 看起来你的 py 文件提到了template.html,但你说你的文件叫做home.html,你应该检查你是否在两个地方写了不同的文件名