【问题标题】:jinja2 template not found and internal server error找不到 jinja2 模板和内部服务器错误
【发布时间】:2017-07-16 21:17:05
【问题描述】:

Python 代码:

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")

def hello():

    return render_template('testing.html')

if __name__ == "__main__":
    app.run()

HTML 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>My name is pk</h1>
</body>
</html>

还有如何在 pycharm 社区版中启用 jinja2。我直接在同一个项目中创建html文件和.py文件

【问题讨论】:

  • 您能否向我们展示完整的错误,以及您是如何构建文件和目录的?
  • 确保您的“testing.html”文件位于模板文件夹中。如果你能展示你的应用结构就更好了。
  • @coralvanda 我通过使用下面提到的策略得到了解决方案。谢谢,请继续回答我的问题。
  • @thangn 是的,文件结构有问题,感谢您的建议。
  • 如果可以的话,请帮我解决这个问题stackoverflow.com/questions/67661017/…

标签: python flask pycharm jinja2


【解决方案1】:

flask 文件结构

|-app
|--templates // where your html files must be in
|--static // where your js and css files must be in
|--.py files
|--other packages

如果你已经下载了烧瓶包,你的系统中也启用了 jinja。

【讨论】:

【解决方案2】:

默认情况下,Flask 会在您应用的根目录中查找 templates 文件夹。

http://flask.pocoo.org/docs/0.10/api/

template_folder – 包含模板的文件夹 由应用程序使用。默认为根目录中的“模板”文件夹 应用程序的路径。

所以你有一些选择,

  1. template重命名为templates
  2. 提供 template_folder 参数,让烧瓶应用程序识别您的 template 文件夹:

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

Flask 期望templates 目录与创建它的模块位于同一文件夹中; 你需要告诉 Flask 去别处看看:

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

这是因为路径是相对于当前模块路径解析的。

您不能拥有每个模块的模板目录,除非使用blueprints。一种常见的模式是使用templates 文件夹的子目录来代替您的模板分区。你会使用templates/pages/index.html,加载render_template('pages/index.html')等。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-05-28
  • 2013-10-24
  • 2011-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
  • 2012-04-06
相关资源
最近更新 更多