我有一個帶有全域變數的 python 燒瓶應用程式,它從 Redis 讀取一些資料。我有另一個行程獨立更新 Redis 中的資料,它會 ping 燒瓶應用程式(即端點 /reload-redis-data),告訴燒瓶應用程式用 Redis 中的最新資料更新該全域變數。
涉及3個檔案:
- 應用程式.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)
- 實用程式.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=}")
- 函式.py
from util import a
def f():
global a
print(f"In function f {a=}")
設定是:
- 在 Redis 中
set a 1 - 在服務器啟動時,
load_redis_config()將被呼叫并加載a-> 列印 1 - /test -> 列印 1
- 在 Redis 中
set a 2 - ping
/reload-redis-config,load_redis_config()將列印a更改為 2 - /test -> 我希望它被更改為 2,因為
a它是一個在步驟 5 中更新的全域變數,但在函式內 fa仍然是 1。
我的蹤跡:
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 -
基本上我的問題是,為什么function不選擇更新的全域變數a?有什么我遺漏的東西或任何概念嗎?
uj5u.com熱心網友回復:
因此,您的function.py檔案會在服務器啟動時呈現一次,然后在呼叫f()時只呈現函式/test。由于您只在腳本中匯入了a一次變數function.py,并且僅在服務器啟動時才呈現,因此腳本不會檢查它是否在util.py再次f()呼叫時更新。
為了解決這個問題,在你的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=}")
def get_a():
return a
load_redis_config()
print(f"At server start {a=}")
在你function.py
from util import get_a
def f():
a = get_a()
print(f"In function f {a=}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/525193.html
