Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to Flask Global Variables in Blueprint Apps

my source code has this structure:

main.py:

from flask import Flask, g
app = Flask(__name__)
with app.app_context():
    g.my_db = PostgreSQL()
    app.register_blueprint(my_app, url_prefix="/my_app")

my_app.py:

from flask import Blueprint, g
my_app = Blueprint("my_app", __name__)
@my_app.route("/")
def index():
    return g.my_db.fetch_all()   <<< ERROR

but it shows this error:

AttributeError: '_AppCtxGlobals' object has no attribute 'my_db'

Even when I try to use g outside of app context, it shows this error:

RuntimeError: Working outside of application context.

So how to set and access to global variables in Flask?

like image 927
mortymacs Avatar asked May 08 '18 12:05

mortymacs


People also ask

Can I use global variables in Flask?

More often than not, what you're really trying to do, when you use global variables in Flask, is to save user entered or recorded information across different routes, while concurrently allowing for modifications to the same. As it happens, Flask has an inbuilt library for this functionality : Flask Sessions.

How do I run a Flask app with blueprints?

To use any Flask Blueprint, you have to import it and then register it in the application using register_blueprint() .

What is the use of G in Flask?

g is an object for storing data during the application context of a running Flask web app. g can also be imported directly from the flask module instead of flask. globals , so you will often see that shortcut in example code.


1 Answers

This happens because the data are lost when the context (with app.app_context()) ends (doc).

Inside the context, everything is ok :

from flask import Flask, g
app = Flask(__name__)
with app.app_context():
    g.my_db = 'database ok'
    print(g.my_db)

# >>> this prints 'database ok'

But outside, you cannot access the attribute :

from flask import Flask, g
app = Flask(__name__)
with app.app_context():
    g.my_db = 'database ok'

print(g.my_db)

# >>> this throws RuntimeError: Working outside of application context

even if you create a new context:

from flask import Flask, g
app = Flask(__name__)
with app.app_context():
    g.my_db = 'database ok'

with app.app_context():
    print(g.my_db)

>>> this throws AttributeError: '_AppCtxGlobals' object has no attribute 'my_db'

Your best call should be to declare the database object before the context, and then import it. Or maybe you can create it directly inside my_app.py where you need it ?

like image 118
PRMoureu Avatar answered Oct 16 '22 17:10

PRMoureu