What's the right approach for calling functions after a flask app is run?

扶醉桌前 提交于 2019-11-28 06:17:14

The duplicate output from your function can be explained by the reloader. The first thing it does is start the main function in a new thread so it can monitor the source files and restart the thread when they change. Disable this with the use_reloader=False option.

If you want to be able to run your function when starting the server from a different module, wrap it in a function, and call that function from the other module:

def run_server(dom):
        _run_on_start("%s" % dom)
        app.run(debug=True, use_reloader=False)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        raise Exception("Must provide domain for application execution.")
    else:
        DOM = sys.argv[1]
        run_server(DOM)

The "right approach" depends on what you're actually trying to accomplish here. The built-in server is meant for running your application in a local testing environment before deploying it to a production server, so the problem of starting it from a different module doesn't make much sense on its own.

Probably you were looking for Flask.before_first_request decorator, as in:

@app.before_first_request
def _run_on_start(a_string):
    print "doing something important with %s" % a_string
from flask import Flask

def create_app():
    app = Flask(__name__)
    def run_on_start(*args, **argv):
        print "function before start"
    run_on_start()
    return app

app = create_app()

@app.route("/")
def hello():
    return "Hello World!"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!