-1

My question is: i have a flask server which receives data and another python script which use that data everytime they change.

More precisely I have a class where the data is set by Flask and then the other script uses getters to get the new data.

I tried to share the same class instance across the two file but it doesn't work.

Flask app (app.py):

from user import Usert
# ...
user = User()
@app.route('/', methods=["GET", "POST"])
@app.route('/index', methods=["GET", "POST"])
def index():
    if request.method == "POST":
        data = request.get_json()
        s1 = json.dumps(data)
        d2 = json.loads(s1)
        
        if("something" in d2):   
            user.set_something = #new value received

        # other things

    return render_template('index.html')

User class (user.py):

class User:
    def __init__(self):
        self._something = 0

    @property
    def get_something(self):
        return self._something

    @get_something.setter
    def set_something(self, value):
        self._something = value

And then the file who should use the getter:

import user
from app import user

# check if something is changed
# only it is changed
print(user.get_something)

Can you help me?

gio
  • 1
  • 2

1 Answers1

-1

The flow of what you have should work. I modified your code below to isolate demo-ing the sharing of the class across your files. Note that I renamed the local variable "user" to "my_user" to avoid confusion and I added a main method.

Using your same user.py, the following will print out 5 when main.py is run:

app.py:

from user import User

my_user = User()
my_user.set_something = 5

main.py:

import user
from app import my_user

def main():
    print(my_user.get_something)

if __name__ == "__main__":
    main()
  • Thank you so much for your answer but it still doesn't work. If i set user.set_something outside "def index()" the main.py see the change but when i set the variable inside the function then the main can't see the new value. What should I do? – gio Aug 07 '22 at 12:41
  • One of two issues occurs to me. One, it might be that your index() is not being called. Two, it might be that your def index(): is treating "user" as a local variable rather than a global one. You could try using the global keyword for user within that function definition – jonathanfuchs Aug 07 '22 at 12:56
  • I tried to use the global keyword and still the main.py doesn't see the new value. The index () is called by Flask (app.py) automatically cause the @route decorator – gio Aug 07 '22 at 13:00
  • Nothing else occurs to me at the moment, based on what I know of your code. I'd make sure that all the conditions in your conditional statements leading up to setting the value are True, and that your route is successfully being hit. – jonathanfuchs Aug 07 '22 at 13:04
  • Yes, on the app.py the new value is always being updated, the problem is that in the main.py i can't see the new value – gio Aug 07 '22 at 13:07