【问题标题】:Flask: Multiple blueprints interfere with each otherFlask:多个蓝图相互干扰
【发布时间】:2014-03-05 07:04:28
【问题描述】:

我正在用蓝图测试 Flask。我的应用有两个蓝图:

  1. 基础
  2. 意见

base/__init__.py

base = Blueprint('base', __name__, static_folder='static', template_folder='templates') 
#http://server.com/base

意见/__init__.py

opinions = Blueprint('opinions', __name__, static_folder='static', template_folder='templates')
#http://server.com/opinions

__init__.py

app = Flask(__name__)
from app.base import views 
from app.base import base
app.register_blueprint(base, url_prefix='/base')

from app.opinions import views
from app.opinions import opinions
#app.register_blueprint(opinions, url_prefix='/opinions')  <-- Uncommenting this line causes issues

如果我只注册其中一个蓝图,一切都会运行良好。但是,如果我注册两个蓝图,模板总是从opinions 加载。例如,如果我点击 http://server.com/base , index.html 会从意见文件夹中挑选出来。 Flask 文档没有提到任何关于 'template_folder' 命名空间冲突的内容。

PS - 我想知道处理多个蓝图的替代方法。我不太习惯从两个不同的蓝图导入views 文件。有什么更好的方法来做到这一点?

【问题讨论】:

  • 请在您的模板和生成的 html 行中包含一个静态的示例用法。
  • @PaoloCasciello - 你的评论确实有帮助。不是静态文件,而是选择了错误的模板。我已经适当地编辑了这个问题。

标签: python flask


【解决方案1】:

蓝图模板目录是全局注册的。它们共享一个命名空间,以便您的应用可以在必要时覆盖蓝图的模板。文档中简要提到了这一点。

因此,您不应将意见模板命名为index.html,而应命名为opinions/index.html。乍一看,这使得路径很尴尬 (…/opinions/templates/opinions/…),但增加了在不更改蓝图内容的情况下自定义“罐装”模板的灵活性。

【讨论】:

    猜你喜欢
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 2023-01-31
    相关资源
    最近更新 更多