如何使用 python Flask MVC 呈现 index.html

zab*_*mba 0 python flask python-2.7

这对我来说绝对是一个新领域,我只是对它的工作方式感到困惑

烧瓶服务器

$ more flask-hello-world.py 
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return render_template('index.html') #"Hello World!"

if __name__ == "__main__":
    app.run()
Run Code Online (Sandbox Code Playgroud)

索引.html

$ more index.html 
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>untitled</title>
</head>
<body>

Hello worlds
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

测试

$ curl 127.0.0.1:5000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request.  Either the server is overloaded or there is an error in the application.</p>
Run Code Online (Sandbox Code Playgroud)

当我return "Hello World!"正常工作时。为什么我尝试时会出错return render_template('index.html')

bak*_*kal 5

首先,您应该为 Flask 应用程序打开调试,这样您就会看到一个有意义的错误,而不是预制的HTTP 500 Internal Server Error

app.debug = True
app.run()
Run Code Online (Sandbox Code Playgroud)

或者

app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)

您的 Flask 应用程序可能有什么问题

从你的源代码我看到你没有导入 render_template

所以这至少是一个问题,解决它:

from flask import Flask, render_template
# The rest of your file here
Run Code Online (Sandbox Code Playgroud)

模板名称和目录

template_folder 您可以使用一个参数来告诉 Flask 在哪里查找模板。根据链接的文档,该值默认为templates这意味着 Flask 默认在templates默认调用的文件夹中查找模板。因此,如果您的模板位于项目根目录而不是文件夹中,请使用:

例如,如果您的模板在同一目录中,则是应用程序:

app = Flask(__name__, template_folder='.') # '.' means the current directory
Run Code Online (Sandbox Code Playgroud)