【问题标题】:Is there a way to make all pages in a Flask app show the same content? [duplicate]有没有办法让 Flask 应用程序中的所有页面显示相同的内容? [复制]
【发布时间】:2021-12-08 20:20:43
【问题描述】:

我正在开发一个 Flask 应用程序,我想添加一个使用变量控制的自定义维护模式页面。除了创建 if-then 语句检查变量是否为真之外,还有其他方法可以做到这一点:例如我会做什么:

@app.route("/mypage")
def mypage():
  if (maintenance_mode == 1):
      return render_template("maintenance.html")
  return "response"

我想在不使用 if-then 语句的情况下执行此操作,最好只使用 1 @app.route

【问题讨论】:

  • 为什么使用 if 语句不是一个令人满意的解决方案?您正在尝试执行条件逻辑,这正是它的目的。
  • 我的网站有大约 50 个单独的页面,因此这样做需要很长时间并且效率不高。
  • 我可以,但我不想这样做,很高兴知道以供将来参考。
  • 这不会是明显的性能明智。但这是否意味着您也有 50 个单独的维护页面?或者它只是 1 并且现在每条路由都应该重定向到那个?
  • 我没有 50 个单独的维护页面,但我确实有 50 个页面需要重定向。

标签: python flask


【解决方案1】:

您甚至可能不需要烧瓶,并且可以在其他级别上控制它,但烧瓶here 是这样做的好例子。

建议添加@app.before_request并查看维护标志。 (@app.before_request 将在所有请求之前调用,因此您不需要对所有 50 条路由进行维护检查。

@app.before_request
def check_under_maintenance():
    if maintenance_mode == 1:  #this flag can be anything, read from file,db or anything
        abort(503) 

@app.route('/')
def index():
    return "This is Admiral Ackbar, over"

@app.errorhandler(503)
def error_503(error):
    return render_template("maintenance.html") 

【讨论】:

    猜你喜欢
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    相关资源
    最近更新 更多