Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain a Class instance for each User's session in Flask? [duplicate]

I am currently building a web application built on Flask Framework with around 10 user accounts in the future when the application has been finished.

There is a Class with heavy module (Compute-intensive), built and used in this application, served as one of the frequently used key features, and I have run into some issues and am seeking for some solutions (let's named it as Class A in file a.py)

Originally, I imported the Class A directly into one of the view file, and created a route function for it, that once an user clicks the button which invokes this route, the route function will then create an instance of Class A, and this instance runs based on received data (like Json). But I found the system can be slow down as the instance of Class A has to be created every single time when the user uses the feature frequently, (also there can be 10 users), and Class A is too heavy to be created again and again.

Therefore I am thinking is there anyway that I can create the instance of Class A for only one time (e.g., the time that the Flask application starts), and each logged in user can access this instance rather than create it over and over again?

Thanks in advance

like image 724
nonemaw Avatar asked Jan 26 '26 12:01

nonemaw


1 Answers

Flask Requests are stateless, so to preserve data for a user across requests the options are limited. Here are some ideas:

  1. Serialize the class instance, store it in a flask session (just a wrapper for browser session cookies), retrieve later.

  2. Store it in a database, retrieve later when needed

  3. Pickle it, dump it using user name, retrieve when needed.

Alternatively, depending on the application, a cache solution might good enough (ig Flask-caching). The route/view would instantiate the class the first time it's called and return a value.

If the view is called again with the same arguments/data, the previous return value is returned without running the view function again.

like image 194
gtalarico Avatar answered Jan 29 '26 02:01

gtalarico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!