問題描述:當在python的flask中定義全局變量之后,當其他模塊修改全局變量,flask中的api運行時讀取的全局變量值還是定義時的初始值。
在https://stackoverflow.com/questions/23457658/flask-global-variables有人遇到了同樣的問題。
I am trying to find out how to work with global variables in Flask:
gl = {'name': 'Default'}
@app.route('/store/<name>')
def store_var(name=None):
gl['name'] = name
return "Storing " + gl['name']
@app.route("/retrieve")
def retrieve_var():
n = gl['name']
return "Retrieved: " + n
Storing the name and retrieving it from another client works fine. However, this doesn't feel right: a simple global dictionary where any session pretty much simultaneously can throw in complex objects, does that really work without any dire consequences?
下面有人說了導致問題的原因:
No, it doesn't work, not outside the simple Flask development server.
WSGI servers scale in two ways; by using threads or by forking the process. A global dictionary is not a thread-safe storage, and when using multi-processing changes to globals are not going to be shared. If you run this on a PAAS provider like Google App Server, the processes aren't even forked; they are run on entirely separate machines even.
可能的解決方法:
Use some kind of backend storage instead; a memcached server, a database server, something to control concurrent access and share the data across processes.
另一個可能的解決方法:
參考:https://www.cnpython.com/qa/78502
你不需要一個全局變量來實現這一點,並且說真的,你在未來的任何時候都不需要它們,因為使用全局變量是一種不好的做法。有關詳細信息,請參閱此鏈接,why are global variables evil?
現在談到您的問題,您可能需要flask的g模塊,該模塊創建一個上下文,該上下文在同一用戶的多個請求上保持不變。你可以這樣做:
from flask import g
...
def get_messages():
messages = getattr(g, '_messages', None)
if messages is None:
g._messages = [] # to store messages you may use a dictionary
return g._messages
def add_message(message):
messages = get_messages()
messages.append(message)
setattr(g, '_messages', messages)
return messages
記住,對於每個用戶,應用程序都會創建一個不同的線程,這樣既不會共享變量,也不會共享它們的值。因此,對於每個用戶,都有一個不同的g,但它將在同一個用戶的多個請求上持續存在。希望有幫助!