如何从python flask中的不同目录引用html模板

Big*_*Boy 18 python directory path flask

@app.route('/view', methods=['GET', 'POST'])
def view_notifications():
    posts = get_notifications()
    return render_template("frontend/src/view_notifications.html", posts=posts)
Run Code Online (Sandbox Code Playgroud)

所以在我project/backend/src/app.py的代码中.我如何引用project/frontend/src/view_notifications.html我尝试使用的模板,..但它一直在说找不到路径.还有另一种方法我应该这样做吗?

[Tue Jun 23 12:56:02.597207 2015] [wsgi:error] [pid 2736:tid 140166294406912] [remote 10.0.2.2:248] TemplateNotFound: frontend/src/view_notifications.html
[Tue Jun 23 12:56:05.508462 2015] [mpm_event:notice] [pid 2734:tid 140166614526016] AH00491: caught SIGTERM, shutting down
Run Code Online (Sandbox Code Playgroud)

kyl*_*e.a 29

Flask正在寻找templates/frontend/src/view_notifications.html您的模板文件.您需要将模板文件移动到该位置或更改默认模板文件夹.

根据Flask文档,您可以为模板指定不同的文件夹.它默认templates/位于您应用的根目录中:

import os
from flask import Flask

template_dir = os.path.abspath('../../frontend/src')
app = Flask(__name__, template_folder=template_dir)
Run Code Online (Sandbox Code Playgroud)

更新:

在Windows机器上自己测试后,模板文件夹确实需要命名templates.这是我使用的代码:

import os
from flask import Flask, render_template

template_dir = os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
template_dir = os.path.join(template_dir, 'frontend')
template_dir = os.path.join(template_dir, 'templates')
# hard coded absolute path for testing purposes
working = 'C:\Python34\pro\\frontend\\templates'
print(working == template_dir)
app = Flask(__name__, template_folder=template_dir)


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

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

有了这个结构:

|-pro
  |- backend
    |- app.py
  |- frontend
    |- templates
      |- index.html
Run Code Online (Sandbox Code Playgroud)

更改'templates'to的任何实例'src'并重命名templates文件夹会'src'导致收到相同的错误OP.

  • 您可能必须将 src 文件夹重命名为“templates” (2认同)

Mac*_*ias 18

一个面糊的解决方案是直接去没有 os.path.abspath 这样的:

from flask import Flask

app = Flask(__name__, template_folder='../../frontend/src')
Run Code Online (Sandbox Code Playgroud)

  • 怎样使用相对路径更好?我并不反对,但你应该在你的回答中解释原因。 (2认同)
  • 如果文件结构发生变化,您还需要调整解决方案中的代码。您还使用相同的相对路径,因此我的解决方案仅增加了可读性,但不会引入额外的维护开销。 (2认同)