How to share the global app object in flask?

后端 未结 6 668
被撕碎了的回忆
被撕碎了的回忆 2021-01-30 16:28

I am using flask and trying to the following.

I have defined a main.py file through which I want to run my app ie python main.py -

from flask import Fla         


        
6条回答
  •  孤独总比滥情好
    2021-01-30 17:25

    Regarding import and use of current_app from flask in a "helper" python function in a separate source file, this works as long as a current app context has already been set up (E.g. web request received). I have a case where, during application initialization (app.run not yet invoked), app.logger is invoked in the helper function.

    Before I fixed it (see below), I got a stack trace punctuated by "RuntimeError: Working outside of application context".

    Sample solution:
    main.py:

    import helper
    ...
    app = Flask(__name__.split('.')[0],
            template_folder="templates",
            static_folder="static")
    ... 
    # Fix: Create an app context
    with app.app_context():
        helper.dbopen(...)
    ...
    app.run(...)
    

    helper.py:

    from flask import current_app as app
    ...
    def dbopen():
        app.logger.info(...)
        ...
    

提交回复
热议问题