【问题标题】:How to render index.html using python Flask MVC [duplicate]如何使用 python Flask MVC 渲染 index.html [重复]
【发布时间】:2016-05-02 00:00:31
【问题描述】:

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

烧瓶服务器

$ 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()

index.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>

测试

$ 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>

当我return "Hello World!" 时,它确实可以正常工作。为什么我在尝试return render_template('index.html') 时会收到错误消息?

【问题讨论】:

  • 您能分享一下您的项目结构吗?
  • 我也试过了,所有文件都在同一个文件夹中......实际上这很可能是问题......

标签: python python-2.7 flask


【解决方案1】:

首先你应该turn on debugging for your Flask app,这样你就会看到一个有意义的错误,而不是一个固定的HTTP 500 Internal Server Error

app.debug = True
app.run()

app.run(debug=True)

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

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

所以这至少是一个问题,用以下方法解决它:

from flask import Flask, render_template
# The rest of your file here

模板名称和目录

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

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

app = Flask(__name__, template_folder='.') # '.' means the current directory

【讨论】:

  • 我将.pyindex.html 放在同一个文件夹中……这就是问题所在吗?!模板应该放在一个特殊的文件夹中?
  • 是的 templates 是默认值,但我提供了代码让它在与烧瓶应用程序相同的文件夹中查找模板
【解决方案2】:

您需要将模板放在templates 文件夹中,或者将其覆盖在:

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

【讨论】:

  • 这就是我的问题的一部分。干杯伙伴。
猜你喜欢
  • 2019-03-10
  • 1970-01-01
  • 1970-01-01
  • 2013-05-12
  • 2022-01-25
  • 1970-01-01
  • 2016-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多