如何在python烧瓶中设置一个全局变量? [英] How to set a global variable in python flask?
问题描述
我想设置一个全局变量并将其用作各种函数的触发器。每个用户都有一个单独的全局变量。这用于跟踪以前的消息数据并进行对话。问题是如何为每个用户管理一个单独的全局变量?应用程序在我将其部署到服务器后运行。当我尝试更改全局变量时,此变量适用于每个用户,而不仅仅是触发其更改的单个用户。
我使用没有a DB。
谢谢。
这是一个全局变量,并且真正说出你将来不需要它们,因为使用全局变量是一种不好的做法。有关详细信息,请参阅此链接,为什么全局变量是邪恶的?
<现在来解决你的问题,你可能需要使用
g
模块来创建一个上下文,该上下文保持来自同一用户的多个请求。你可以这样做: from flask import g
...
def get_messages():
messages = getattr(g,'_messages',None)
如果消息是None:
g._messages = []#使用字典
return g._messages
def add_message(message):
messages = get_messages()
messages.append(message)
setattr(g,'_messages',messages)
返回消息
每个用户都创建了不同的应用程序线程,因此既不共享变量,也不共享它们的值。因此,对于每个用户来说,都会有不同的 g
,但它会持续来自同一用户的多个请求。希望它有帮助!
I would like to set a global variable and use it as a trigger of various functions. Each user has a separate global variable. This is used to keep track of previous message data and proceed a conversation. The problem is that how can I manage a separate global variable to each user? The app is running once I deployed it in the server. When I attempt to change the global variable, this variable applies to every user, not just that single user who triggered its the change.
I'm using python flask without a DB.
Thank you.
You don't need a global variable for this and truly speaking you won't need them anytime in the future as it is a bad practice to use global variables. Refer to this link for details, why are global variables evil?
Now coming to your problem, you probably need g
module of flask which creates a context which persist over multiple requests from the same user. You can do something like this:
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
And remember for each user a different thread of the app is created so the neither the variables are shared nor their values. So for each user there will be a different g
but it will persist over multiple requests from the same user. Hope it helps!
这篇关于如何在python烧瓶中设置一个全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!