5

Similar to this question, I want to share one variable among an entire Flask application (all requests).

I am compiling a large data file (considerable overhead) and want to do the compilation as little as possible - storing the result in a variable so it can be accessed later. Using flask.g won't work because it is wiped clean between requests.

In a Reddit post six years ago, Armin Ronacher (creator of Flask) said:

You can just attach it to the application object and access it via flask.current_app.whatever_variable.

Here are my two questions:

A) Is this still the recommended practice?

B) Are these two methods (attaching to current_app or app inside an application factory) equivalent?

Using current_app:

from flask import current_app
current_app.my_var = <<file>>

Using an application factory:

def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_pyfile(config_filename)
    app.my_var = <<file>>
    ...
    return app
tzazo
  • 323
  • 3
  • 13

1 Answers1

0

Normally in my projects i create a Globals.py to use globals variables in every part of my program, like this:

from celery import Celery
from flask_babel import Babel
from flask_marshmallow import Marshmallow
from flask_socketio import SocketIO
from flask import json, Flask

app: Flask = None
marshmallow: Marshmallow = Marshmallow()
socket = SocketIO(async_mode="eventlet", json=json)
celery: Celery
babel = Babel()
current_user = None


def init_globals(currentApp):
    global marshmallow
    global app
    global socket
    global celery
    global babel
    app = currentApp
    marshmallow.init_app(app)
    babel.init_app(app)
    socket.init_app(app)

    celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)

And do this in main.py

import Globals
app = Flask(__name__)
Globals.init_globals(app)
Caio Filus
  • 705
  • 3
  • 17