【问题标题】:Flasks blueprint not finding templates or static in root directory烧瓶蓝图在根目录中找不到模板或静态文件
【发布时间】:2020-04-22 21:37:32
【问题描述】:

我正在重构我的烧瓶应用程序以使用蓝图,但我似乎无法通过蓝图在应用程序的根目录中找到模板或静态目录。模板/静态文件仅在我将它们的文件夹放在蓝图的目录中时才被识别,如果文件仅由该特定蓝图使用,那会很好,但是我需要其他模块也能够访问它们(例如基础.html 模板)。我已经尝试在蓝图设置中设置模板和静态文件夹位置,即。

bp = Blueprint('main', __name__,
           template_folder='templates',
           static_folder='static')

以及将其留空(试图使其默认查看根目录)

bp = Blueprint('main', __name__)

我也尝试过明确输入路径。

template_folder='app/templates'

无济于事。

我的应用程序目录如下所示(将我的名称替换为通用目录名称并省略了其他模块,因为我试图让这个首先工作):

library root/
   __init__.py
   setup.py
   app/
      venv/
      templates/
         base.html
         home.html
      static/
         css,js & img files
      blueprint/
         __init__.py

库根(app)/__init__.py 看起来像这样

import os

from flask import Flask


app = Flask(__name__)

def init(app):
    #config init...

    from app.main import bp as main_bp

    app.register_blueprint(main_bp)
    print (app.url_map)

init(app)

if __name__ == "__main__":
    init(app)

    app.run(
        host=app.config['ip_address'],
        port=int(app.config['port']))

blueprint/__init__.py 看起来像这样:

from flask import Blueprint

# Set up a Blueprint
bp = Blueprint('main', __name__,
               template_folder='templates',
               static_folder='static')

#without setting the template & static locations
#bp = Blueprint('main', __name__)

from flask import render_template


@bp.route('/')
def root():
    return render_template('home.html'), 200

我的app.url_map 输出如下所示:

 <Rule '/static/<filename>' (HEAD, GET, OPTIONS) -> static>])
Map([<Rule '/' (HEAD, GET, OPTIONS) -> main.root>,
 <Rule '/' (HEAD, GET, OPTIONS) -> main.root>,
 <Rule '/static/<filename>' (HEAD, GET, OPTIONS) -> static>])

有人对我做错了什么有任何想法吗?据我在各种蓝图教程中看到的,应用程序查找模板文件夹的默认位置是根目录,然后是蓝图目录,为什么不是呢?

【问题讨论】:

    标签: python flask


    【解决方案1】:

    init.py 应该在 app 目录下,将其从库根目录移动到 app 目录即可解决此问题。

    【讨论】:

    • 正如我所说,我也尝试过(参见我的第二个代码 sn-p);它不起作用。
    • ok,在蓝图目录下新建文件 route.py 并将代码从 init.py 移动到 route.py ,keey init.py 为空.
    • init.py 应该在 app 目录中,我可以看到这是在库根目录中,尝试在 app 中移动它
    • 啊,太好了,做到了!出于某种原因,PyCharm 不断在根目录中创建新的 init.py 文件。谢谢!
    • 感谢您的确认,根据上次评论更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多