Flask路由启动前如何运行功能? [英] How to run function before Flask routing is starting?

查看:216
本文介绍了Flask路由启动前如何运行功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to do call function before Flask routing is starting working. Where I should to put function to make it called at service start. I did:

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

推荐答案

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

If i were you, I'd put it in a function creating an app, like:

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()

当发现任何设置错误时,这将允许您执行任何必要的步骤.您也可以在该功能中执行路由.我已经在此处编写了用于分隔此过程的函数:

This will allow you to perform any necessary steps when you discover any settings are wrong. You can also perform routing in that function. I've written such function to separate this process here:

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

这篇关于Flask路由启动前如何运行功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆