python怎样设置全局变量_如何在python烧瓶中设置一个全局变量?

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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值