【问题标题】:How to run function before Flask routing is starting?如何在 Flask 路由开始之前运行函数?
【发布时间】:2017-10-05 13:04:26
【问题描述】:

我需要在 Flask 路由开始工作之前执行调用功能。我应该在哪里放置函数以使其在服务启动时调用。我做到了:

app = Flask(__name__)
def checkIfDBExists(): # it is my function
    if not DBFullPath.exists():
        print("Local DB do not exists")
    else:
        print("DB is exists")

checkIfDBExists()

@app.route("/db", methods=["POST"])
def dbrequest():
    pass

【问题讨论】:

  • 你的解决方案有什么问题?
  • 请提供更多细节。

标签: python flask


【解决方案1】:

如果我是你,我会把它放在一个创建应用程序的函数中,比如:

def checkIfDBExists(): # it is my function
    if not DBFullPath.exists():
         print("Local DB do not exists")
    else:
         print("DB is exists")

def create_app():
    checkIfDBExists()
    return Flask(__name__)

app = create_app()

这将允许您在发现任何设置错误时执行任何必要的步骤。您还可以在该功能中执行路由。我写了这样的函数来分离这个过程here

def register_urls(app):
    app.add_url_rule('/', 'index', index)
    return app

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-03
    • 2017-05-15
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 2021-04-05
    • 2018-11-17
    • 2016-03-11
    相关资源
    最近更新 更多