How to share the global app object in flask?

后端 未结 6 771
被撕碎了的回忆
被撕碎了的回忆 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:24

    Just import it from your other files. Perhaps the best way to do this is to put your app object in one single file and have everything else import from it.

    For example, your main.py could still have:

    from flask import Flask
    from view import tags
    
    app = Flask(__name__)
    

    And then in other files, you could do:

    from .main import app
    

    or, if outside your package, just use the complete string

    from mypackagename.main import app
    

    One thing to be careful of is circular imports. The easiest way to handle this issue is to create your app first and then import whatever else you need to from your base file after you create it.

    So for example:

    from flask import Flask
    app = Flask(__name__)
    
    # do some stuff with app
    from .views import view1, view2
    from .server import run
    

    So long as you put the imports after you've created app, like the above, you shouldn't have an issue with circular imports.

提交回复
热议问题