问题描述:当在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,但它将在同一个用户的多个请求上持续存在。希望有帮助!