0

In my flask application, I have to instantiate an object (no parameters are used in its instantiation), and it takes around 30 seconds to create (let's call the resulting object 'my_obj'). After a user fill out a text box in my website, I call 'my_obj.create(text)' and I pass in the text from the input, and this line returns a string as an output (calling the 'create' method doesn't change anything about 'my_obj'). Since I don't want to repeatedly instantiate the 'my_obj' object due to the long wait time, I was considering instantiating the 'my_obj' only one time (for all users) at the beginning of my file. However, I don't exactly know the mechanics of how Flask uses global-scoped objects in the context of multiple simultaneous users. Is it safe for me to use 'my_obj' in the global scope, or do I have to place the object inside of a view function?

carrot_142
  • 33
  • 1
  • 5
  • I don't know why my question was closed. The link to the 'similar question' is about global variables that are changing. My question is explicitly about global variables that don't change. Is there a way for somebody to 'unclose' this question? – carrot_142 Jul 09 '21 at 01:31
  • The answer to the similar question makes clear that Flask provides no mechanism for storing data global to all clients except during a request (the `g` object). As mentioned in that answer or anyway on that page, alternatives include using redis, memcached, or a database. In your use case, an in-memory solution would be faster than a file-based solution (which includes databases). However, the easiest approach may just be to pickle the object to a file on creation, and then `load` it for each user. – BrianO Jul 09 '21 at 01:54

0 Answers0