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

2024-10-02 08:16:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在烧瓶路由开始工作之前做调用函数。我应该把函数放在哪里,以便在服务启动时调用它。我做到了:

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

Tags: 函数nameappflask路由db烧瓶is
1条回答
网友
1楼 · 发布于 2024-10-02 08:16:12

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

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

^{pr2}$

相关问题 更多 >

    热门问题