【问题标题】:How do you route multiple apps in Flask Blueprints correctly?如何在 Flask 蓝图中正确路由多个应用程序?
【发布时间】:2021-06-15 16:40:04
【问题描述】:

我刚刚重新安排了我的烧瓶站点以支持多个应用程序,但似乎存在多个应用程序的蓝图和路由问题。以下运行,但是当您转到 localhost/backstory 时,呈现的索引是主索引而不是背景索引。我尝试做一些事情,比如在蓝图注册中使用 prefix_url,但这似乎不起作用。

据我所见,Blueprint() 函数指向正确的目录,并且应该为路径 /backstory 引用正确文件夹中的索引。然而,它并没有这样做。我错过了什么?

from flask import Flask
from database import database

# blueprint import
from apps.home.views import home_blueprint
from apps.backstory.views import backstory_blueprint

application = Flask(__name__)

# setup with the configuration provided
application.config.from_object('config.DevelopmentConfig')

# setup all our dependencies
database.init_app(application)

# register blueprint
application.register_blueprint(home_blueprint)
application.register_blueprint(backstory_blueprint)


if __name__ == "__main__":
    application.run()

首页

from flask import Blueprint, request, url_for, redirect, render_template, flash

home_blueprint = Blueprint('home', __name__, template_folder="templates/home")


@home_blueprint.route("/")
def home():
    return render_template('index.html')

背景故事

from flask import Blueprint, request, url_for, redirect, render_template, flash

backstory_blueprint = Blueprint('backstory', __name__, template_folder="templates/backstory")


@backstory_blueprint.route("/backstory")
def backstory():
    return render_template('index.html')

结构

Project
 apps
  backstory
   templates
    backstory
      index.html
    views.py
  home
   templates
    home
      index.html
    views.py
 application.py

【问题讨论】:

    标签: python flask


    【解决方案1】:

    我的模板文件夹位置似乎有误。应该将它指向模板,然后按照 Flask 上的文档将 backstory/index.html 作为 render_template() 位置。

    然后当你想渲染模板时,使用 admin/index.html 作为 查找模板的名称。如果您在加载时遇到问题 正确的模板启用 EXPLAIN_TEMPLATE_LOADING 配置 变量将指示 Flask 打印出它执行的步骤 通过在每个 render_template 调用中定位模板。

    from flask import Blueprint, request, url_for, redirect, render_template, flash
    
    backstory_blueprint = Blueprint('backstory', __name__, template_folder="templates")
    
    
    @backstory_blueprint.route("/backstory")
    def backstory():
        return render_template('backstory/index.html')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      相关资源
      最近更新 更多