烧瓶无法找到模板 [英] Flask unable to find templates

查看:43
本文介绍了烧瓶无法找到模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目结构如下

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 .

My idea is to now import app to every other module to use it to create views. Here in this case there is a module pages.

pages.views 中,我有一些类似的代码

In pages.views I have some code like

from flask import render_template
from mysite.conf import app

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

index.html 位于页面/模板

当我从 run.py (如下所示)运行该应用程序时

When I run this app from run.py which is like below

from mysite.conf import app
app.run()

我收到找不到模板错误.如何解决?以及为什么会这样!

I'm getting template not found error. How to fix it? and why is this happening!

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

I'm basically a django guy, and facing a lot of inconvenience with importing the wsgi object every time to create a view in every module! It kinda feels crazy -- Which in a way encourages circular imports. Is there any way to avoid this?

推荐答案

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

Flask expects the templates directory to be in the same folder as the module in which it is created; it is looking for mysite/conf/templates, not mysite/pages/templates.

您需要让Flask代替其他地方查看

You'll need to tell Flask to look elsewhere instead:

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

这是相对于当前模块路径的解析路径.

This works as the path is resolved relative to the current module path.

您不能拥有每个模块的模板目录,除非没有使用蓝图.一种常见的模式是使用 templates 文件夹的子目录代替对模板进行分区.您将使用 templates/pages/index.html ,并加载了 render_template('pages/index.html')等.

You cannot have per-module template directories, not without using blueprints. A common pattern is to use subdirectories of the templates folder instead to partition your templates. You'd use templates/pages/index.html, loaded with render_template('pages/index.html'), etc.

替代方法是在每个子模块中使用 Blueprint 实例;您可以为每个蓝图分配一个单独的模板文件夹,该文件夹用于注册到该蓝图实例的所有视图.请注意,蓝图中的所有路由都必须以该蓝图唯一的公共前缀开头(可以为空).

The alternative is to use a Blueprint instance per sub-module; you can give each blueprint a separate template folder, used for all views registered to that blueprint instance. Do note that all routes in a blueprint do have to start with a common prefix unique to that blueprint (which can be empty).

这篇关于烧瓶无法找到模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆