使用render_template和Flask获取500内部服务器错误
问题描述:
我正在尝试使用Flask呈现HTML模板.我的软件运行良好,现在每次出现 500 Internal Server Error
.如果我只用一个字符串替换 render_template
函数,一切就可以正常进行.我在做什么错了?
I am trying to use Flask to render an HTML template. I had it working great and now each time I get a 500 Internal Server Error
. If I replace the render_template
function just a string, things work fine. What am I doing wrong?
初始化 .py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def homepage():
return render_template("main.html")
if __name__ == "__main__":
app.run()
/templates/
main.html in /templates/
<!DOCTYPE html>
<html lang="en">
<p>test</p>
</html>
答
必须定义template_folder静态文件所在的位置.
The template_folder has to be defined where the static files are located.
如果main.html文件与init.py位于同一文件夹中,则请包含以下代码:
If the main.html file is in the same folder as the init.py, then include the following code:
import os
project_root = os.path.dirname(__file__)
template_path = os.path.join(project_root, './')
app = Flask(__name__, template_folder=template_path)
希望它现在可以正常工作.
Hopefully it works now.