'Storing Objects assigned to user while using Flask [duplicate]

I come here to ask you a question about the way session can handle Objects in Flask. I have a Flask application and I want all my users to have their own object Web_Attributes (this is basically a simple python Class). But the thing is that some Attributes of my Class are also Classes. Thus, the solutions provided by using JSON, for example here and here, do not work because my attributes struggle to be transformed to a key/value model.

I understand that I cannot simply put session[ip_address]=Web_Attributes() even if it is what I wanted because session helps you "carry your data in the browser" and thus the Object structure cannot be kept.

Initially, what I did was to store my Object in a global variable that can "navigate" between my flask route but since I want several users to use the website at once, I can't keep the same global variable since it will be modified by everyone.

One idea I had was to set a dictionary as a global variable with ip adresses as keys and object Web_Attributes as values, so every IP address has it own "session".

Because the global variable is only handled by Python, I think it could be a way to overcome the problem of the structure of the Object. But I wonder whether it is the right way to do it, or if there are any warnings that I need to take into account ?



Solution 1:[1]

IP address is not a unique identifier. Several users may share the same.

If your users are identified (authenticated) you may use the same dict method with the user identifier as the key. While this would work, it raises issues: memory consumption, session data lost on app restart.

Ultimately, you'll be wanting to serialize your stuff either in a session cookie or a local database. (Both raise more or less the same serialization issues you already identified.)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jérôme