Reputation: 16935
I am working on a Flask application that will run a Foo
. Once a Foo
is running, it should be possible to hit endpoints at hostname:8080
to perform some API call that changes the state of the Foo
.
Below is a fairly minimal (though not complete) example. The methods and functions referenced aren't terribly important as the question is about the global object whose state is being affected.
__foo = None
app = Flask(__name__)
@app.route("/start_foo")
def start_foo():
return __foo._do_foo_init() or ""
def run_foo(foo, debug=False):
"""
Entry point for clients to run a foo
:param foo:
:return:
"""
global __foo
__foo = foo
t = threading.Thread(target=delayed_registration, args=(foo,))
t.start()
app.run(host=hostname, debug=debug, port=8080)
When a user calls run_foo
, she will provide a Bar
, which is a subclass of Foo
, but this shouldn't matter.
I was thinking that making the @app.route
a method of a class and have the foo
as a member of the class, but I don't know if this is possible within Flask.
Does anyone have recommendations for how to remove the global __foo
in the above application?
Upvotes: 2
Views: 588
Reputation: 7384
In flask you should store application global objects in flask.g (see the documentation for more information). It is true that this is "local" to the application, but in flask it should be possible to have multiple application in the same python interpreter. The flask documentation states:
Since one of the pillars of Flask’s design is that you can have more than one application in the same Python process.
So everything besides configuration should not be global but local to the flask application.
Upvotes: 1