murtaza52 murtaza52 - 1 year ago 96
Python Question

How to share the global app object in flask?

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 Flask
from view import tags

app = Flask(__name__)

@app.route('/')
def hello_world():
return 'Hello World!'

if __name__ == '__main__':
app.run()


I have defined a package named view in which I will be declaring my different view modules, each having its own routes. view.tags.py -

from flask import Flask
app = Flask(__name__)

@app.route('/e')
def hello_world2():
return 'Hello World!'


So I need to have the global app object in my main.py for running the server, as well as in the view classes of my package for registering the routes. So how do I create the global app object and share it between all classes ?

Thanks,
Murtaza

Answer Source

One way is to create an overall package and adding a __init__.py file under that where you declare all global variables. In your case for example, you can create something like:

myapplication/
    *        __init__.py
    *        myviews/
        *         __init__.py
        *         view.py
        *         tags.py

etc

Now you add the following code in the __init__.py file:

app = Flask(__name__)

You can now use this app variable anywhere as long as you import the package myapplication.

import myapplication.myviews.view