Flask无法找到模板

时间:2014-05-24 15:49:31

标签: python flask

我的项目结构如下

run.py
lib/
mysite/
    conf/
        __init__.py (flask app)
        settings.py
    pages/
        templates/
            index.html
        views.py
        __init__.py

这是mysite.conf.__init__

from flask import Flask

app = Flask(__name__)
app.debug = True

我的想法是现在将app导入到每个其他模块以使用它来创建视图。在这种情况下,有一个模块pages

pages.views我有一些像

这样的代码
from flask import render_template
from mysite.conf import app

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

index.html位于pages/templates

当我从run.py运行此应用时,如下所示

from mysite.conf import app
app.run()

我收到模板未找到错误。 怎么解决?为什么会这样呢!

我基本上是一个django家伙,每次导入wsgi对象以在每个模块中创建视图时都会遇到很多不便!它有点疯狂 - 这在某种程度上鼓励了循环进口。有什么方法可以避免这种情况吗?

3 个答案:

答案 0 :(得分:22)

Flask希望templates目录与创建它的模块位于同一文件夹中;它正在寻找mysite/conf/templates不是 mysite/pages/templates

你需要告诉Flask去别处寻找:

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

这适用于相对于当前模块路径解析的路径。

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

另一种方法是每个子模块使用Blueprint个实例;您可以为每个蓝图指定一个单独的模板文件夹,用于注册到该蓝图实例的所有视图。请注意,蓝图中的所有路径都必须以该蓝图独有的公共前缀(可以为空)开头。

答案 1 :(得分:1)

我也遇到了这个问题,并且是Flask的新手。

针对我的情况的解决方案是在主应用目录中创建一个__init__.py文件,以便将app/转到一个模块中,因为正如Martijn Pieters所指出的,flask期望{ {1}}默认位于主模块目录中。为了重述他的答案,您可以在实例化templates类时重新分配默认目录,例如Flask

因此,简单的目录结构应如下所示:

Flask(__name__, template_folder=any/relative/path/from/app/dir/or/absolute/path/youd/like)

...其中app/ run.py templates/ sample_template.html __init__.py # <---- This was the missing file in my case. 可能看起来像这样:

app.py

答案 2 :(得分:0)

我很确定您在主文件夹上拼错了“模板”。只需重命名

或:

做这样的事情(template_folder = '你的文件所属的文件夹的名称')

from flask import Blueprint
from flask import render_template


views = Blueprint('views',__name__,template_folder='tamplate')




@views.route('/')

def home():

    return render_template("home.html")
相关问题