2

I am running a flask server and would like to initialize one complicated object for each thread at startup. The initialization is slow but only needs to be done once. After the initialization, speed is not an issue. The operations on the objects are no thread safe, but their contents do not change between requests.

How do I do something like this with flask? How can I perform an initialization task on a per thread basis (rather than a per request basis)?

0

1 Answer 1

1

You can store your object in memory. Flask app is right place for such objects, which you want to store.

class FlaskApp(Flask):

    def __init__(self, *args, **kwargs):
        super(FlaskApp, self).__init__(*args, **kwargs)
        self.complex_object = create_my_object()

app = FlaskApp(__name__)

if __name__ == '__main__':
    app.run(debug=True)
Sign up to request clarification or add additional context in comments.

2 Comments

But wouldn't that give me one object per app rather than one object per thread?
As I understand, each thread has one flask app instance. You can check it by printing something to the log on FlaskApp init.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.