Search code examples
flask

Store objects on the Flask object


I need to store an object on my flask.Flask instance. The naive approach would be just assigning an attribute like this.

app = flask.Flask(__name__)
app.my_object = MyObject()

I'm planning on referencing it later in an application context like this:

flask.current_app.my_object

I doubt this method is thread save though. Is there a correct method to do this that is encouraged by Flask? If not, how would you safely implement the approach above?


Solution

  • I ended up with using the config object.

    app.config['MY_OBJECT'] = MyObject()
    

    You can reference it like this in a request.

    current_app.config['MY_OBJECT']