jinja2 模板未找到且内部服务器错误

pk7*_*786 4 python jinja2 pycharm flask

Python代码:

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")

def hello():

    return render_template('testing.html')

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

HTML 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>My name is pk</h1>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

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

小智 5

烧瓶文件结构

|-app
|--templates // where your html files must be in
|--static // where your js and css files must be in
|--.py files
|--other packages
Run Code Online (Sandbox Code Playgroud)

如果您已经安装了 Flask,那么 jinja2 也在您的 python 环境中。


U.S*_*wap 5

默认情况下,Flask 会查找templates应用程序根级别的文件夹。

\n\n
\n

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

\n\n

template_folder \xe2\x80\x93 包含应用程序应使用的模板的文件夹。默认为应用程序根路径中的“templates”文件夹。

\n
\n\n

所以你有一些选择,

\n\n
    \n
  1. 重命名templatetemplates
  2. \n
  3. 提供一个template_folder参数以使templateFlask 应用程序识别您的文件夹:

    \n\n
    app = Flask(__name__, template_folder=\'template\')\n
    Run Code Online (Sandbox Code Playgroud)
  4. \n
\n\n

Flask 期望该templates目录与创建它的模块位于同一文件夹中;\n您需要告诉 Flask 去其他地方查找:

\n\n
app = Flask(__name__, template_folder=\'../pages/templates\')\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

如果不使用blueprints,则不能拥有每个模块的模板目录。常见的模式是使用templates文件夹的子目录来对模板进行分区。你会使用templates/pages/index.html、 加载render_template(\'pages/index.html\')等等。

\n