I have a python flask app with a global variable reading some data from Redis. I have another process that's updating data in Redis independently, and it will ping the flask app (i.e. endpoint /reload-redis-data) to tell flask app to update that global variable with the latest data in Redis.
There are 3 files involved:
- app.py
from re import A
from flask import Flask
from util import load_redis_config
from function import f
app = Flask(__name__)
@app.route("/")
def index():
return "Hello world!"
@app.route("/test")
def test():
f()
return ""
@app.route("/reload-redis-config")
def reload_redis_config():
load_redis_config()
return "reloaded"
if __name__ == "__main__":
app.run("localhost", 3001)
- util.py
import redis
global a
a = ""
def load_redis_config():
con = redis.Redis("localhost", 6379)
global a
a = eval(con.get("a"))
print(f"Updated {a=}")
load_redis_config()
print(f"At server start {a=}")
- function.py
from util import a
def f():
global a
print(f"In function f {a=}")
The setup is:
- in Redis
set a 1
- at server start,
load_redis_config()
will be called and loada
-> print 1 - /test -> print 1
- in Redis
set a 2
- ping
/reload-redis-config
,load_redis_config()
will printa
is changed to 2 - /test -> I'm expecting it to be changed to 2 since
a
is a global variable which is updated in step 5, but within function fa
is still 1.
My trace:
Updated a=1
At server start a=1
* Serving Flask app 'app'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://localhost:3001
Press CTRL+C to quit
In function f a=1
127.0.0.1 - - [28/Oct/2022 14:22:21] "GET /test HTTP/1.1" 200 -
Updated a=2
127.0.0.1 - - [28/Oct/2022 14:22:32] "GET /reload-redis-config HTTP/1.1" 200 -
In function f a=1
127.0.0.1 - - [28/Oct/2022 14:22:35] "GET /test HTTP/1.1" 200 -
Basically my question is, why function
isn't picking up the updated global variable a
? Is there anything or any concept that I'm missing?
from Flask update a global variable with value from Redis
No comments:
Post a Comment