How to run function before Flask routing is starti

2020-05-09 17:08发布

问题:

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

回答1:

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


标签: python flask