How to share the global app object in flask?

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

First, I would suggest to take a look at Blueprints http://flask.pocoo.org/docs/blueprints/ This will help to organize the app easily.

Also take a look at http://flask.pocoo.org/docs/api/#flask.current_app flask.current_app, the way how to get your app instance in other modules.

This link also could be helpful on how to organize and build flask app (it is not ideal for sure, but can give you some ideas) - Large-app-how-to.md

Have fun :)


You can import current_app from flask. It stores a reference to the global application object.

from flask import current_app as app

def home():
    return render_template('base.html', name=app.name)

Tags:

Python

Flask