Flask variable appears to be out of sync

35 views Asked by At

I am building a webserver with Flask, and I need to be able to change specific users' session variables. To do this, I created a variable (foo) in which I store the data that needs to be changed in the session variable. I also created a function with the app.before_request decorator, and that's where I check foo, to see if anything needs to be changed in the current session variable
This is the idea:

foo = {}
@app.route("/admin", methods=["GET","POST"])
def some_admin_route():
    ...
    foo[username] = {'key': 'value'}

@app.before_request
def before_request_func():
    if session['username'] in foo:
        for key in foo:
            session[key] = foo[key]

This works perfectly on my local PC, but when tested on my VPS (using uwsgi), weird things happen. If I refresh multiple times, sometimes the foo variable is empty, sometimes it's not, and when there's two key/value pairs, sometimes both are in the variable, sometimes only one, other times neither.
I also tried using global foo but nothing changed.

1

There are 1 answers

0
Troughy On

I found a solution using Redis. Here's a basic example, it uses hset to store the data, hexists to check if username is present and hget to retrieve the data.

redis = Redis(host='localhost', port=6379, db=0)
@app.route("/admin", methods=["GET","POST"])
def some_admin_route():
    ...
    redis.hset("foo", username, json.dumps({'key': 'value'}))

@app.before_request
def before_request_func():
    if redis.hexists("foo", session[username]):
        bar = json.loads(redis.hget("foo", session[username]).decode("utf-8"))
        for key in bar:
            session[key] = bar[key]
        redis.hdel("foo", session[username])