如何在 Flask 路由启动之前运行函数?

Dmi*_*kov 0 python flask

我需要在 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
Run Code Online (Sandbox Code Playgroud)

gon*_*zor 6

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

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()
Run Code Online (Sandbox Code Playgroud)

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

def register_urls(app):
    app.add_url_rule('/', 'index', index)
    return app
Run Code Online (Sandbox Code Playgroud)