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