python html模块调用,如何从python flask中的其他目录引用HTML模板

@app.route('/view', methods=['GET', 'POST'])

def view_notifications():

posts = get_notifications()

return render_template("frontend/src/view_notifications.html", posts=posts)

So in my project/backend/src/app.py there's this code. How would I reference the template that's in project/frontend/src/view_notifications.html I've tried using .. but it keeps saying the path isn't found. Is there another way I should be doing this?

[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

解决方案

Flask is looking in templates/frontend/src/view_notifications.html for your template file. You either need to move your templates file to that location or change the default template folder.

According to the Flask docs you can specify a different folder for your templates. It defaults to templates/ in the root of your app:

import os

from flask import Flask

template_dir = os.path.abspath('../../frontend/src')

app = Flask(__name__, template_folder=template_dir)

UPDATE:

After testing it myself on a Windows machine the templates folder does need to be named templates. This is the code I used:

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)

With this structure:

|-pro

|- backend

|- app.py

|- frontend

|- templates

|- index.html

Changing any instance of 'templates' to 'src' and renaming the templates folder to 'src' resulted in the same error OP received.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值