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

如何从python中的不同目录引用html模板,python,path,flask,directory,Python,Path,Flask,Directory,所以在我的project/backend/src/app.py中有这样的代码。如何引用项目/frontend/src/view_notifications.html中的模板我尝试使用。但它一直说找不到路径。我还有别的办法吗 @app.route('/view', methods=['GET', 'POST']) def view_notifications(): posts = get_notifications() return render_template("fronten

所以在我的
project/backend/src/app.py
中有这样的代码。如何引用
项目/frontend/src/view_notifications.html中的模板
我尝试使用
但它一直说找不到路径。我还有别的办法吗

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

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

根据Flask文档,您可以为模板指定不同的文件夹。它默认为应用程序根目录中的
模板/

[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
更新:

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

import os
from flask import Flask

template_dir = os.path.abspath('../../frontend/src')
app = Flask(__name__, template_folder=template_dir)
在这种结构中:

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)

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

电池解决方案是不使用os.path.abspath直接运行,如下所示:

|-pro
  |- backend
    |- app.py
  |- frontend
    |- templates
      |- index.html

Flask将自动检测文件夹名称“templates”。因此,您应该在项目目录中创建一个名为templates的文件夹,其中包含您的.py应用程序文件。然后将包含html文件的文件夹放在templates文件夹中。因此,您的代码将是

from flask import Flask

app = Flask(__name__, template_folder='../../frontend/src')

确保路径“frontend/src/view_notifications.html”位于templates文件夹中

我添加了template_folder参数,它仍然在说template not Found它是否告诉您它正在查找哪个文件夹?您是否尝试过
project/frontend/src/view_notifications.html
?是的。不幸的是,它仍然给了我同样的东西。嘿,非常感谢!这真的很有效,让我克服了使用烧瓶的困难!我真的很感激!注意:在Ubuntu 16.04上工作很好:)以什么方式使用相对路径更好?我并不反对,但你应该在回答中解释原因。因为你可以跳过os.path.abspath的用法,在你提出的解决方案中,你也可以使用相对路径,并在此基础上创建一个绝对路径,但它也可以在没有转换的情况下工作。对,它可以工作,但现在如果文件结构发生变化,则需要更改代码。您正在用可维护性/可靠性换取可读性/易用性。这没什么错,但不一定“更好”;只是不同而已。如果文件结构发生变化,您还需要调整解决方案中的代码。您还使用了相同的相对路径,因此我的解决方案只增加了可读性,而不会引入额外的维护开销。
return render_template("frontend/src/view_notifications.html", posts=posts)