最新消息:20210917 已从crifan.com换到crifan.org

【已解决】Flask中的全局变量的值获取不到

Flask crifan 7254浏览 0评论

之前在Flask中创建了一个全局变量,用于保存当前某个用户是否已连接webcoket

    gWsDict[userId] = ws

保存后为:

DEBUG in Websocket [/root/RunningFast/staging/runningfast/resources/Websocket.py:208]:
added new ws for user user-c9353e25-2e28-49c0-ae50-bcc414f1600c , gWsDict={u’user-c9353e25-2e28-49c0-ae50-bcc414f1600c’: <geventwebsocket.websocket.WebSocket object at 0x7fd09d70dde0>}

但是在后来另外一个web请求后,去调用到这个全局变量,但是却得到的是空的值:

DEBUG in Websocket [/root/RunningFast/staging/runningfast/resources/Websocket.py:142]:
gWsDict={}

所以现象是:

Flask中的全局变量的值,无法访问到

目前怀疑,难道是因为开了多个worker,多个线程,而导致的?

所以打算抽空去看看:

(1)是否log中可以输出所属的线程的信息

(2)抽空再去把gunicorn的worker设置为1个,看看效果

flask global variable not get value

Global variable and python flask – Stack Overflow

好像是:Python中的全局变量的使用的问题?需要加上global

【总结】

然后用Python中对于全局变量的对应的语法,即可:

gWsDict = {}
def wsNotifyTaskGrabbed(curTask):
    global gWsDict
    initiatorWs = gWsDict[initiatorId]
    gLog.debug("initiatorWs=%s", initiatorWs)
@sockets.route(‘/users/<userId>/<accesstoken>’)
def userWebsocket(ws, userId, accesstoken):
    global gWsDict
    # store active ws into dict
    gWsDict[userId] = ws

对应log是:

added new ws for user user-c9353e25-2e28-49c0-ae50-bcc414f1600c , gWsDict={u’user-c9353e25-2e28-49c0-ae50-bcc414f1600c’: <geventwebsocket.websocket.WebSocket object at 0x7f2a23414de0>}
initiatorWs=<geventwebsocket.websocket.WebSocket object at 0x7fe34d7abde0>

【后记】

后来看到:

Are global variables thread safe in flask?:learnpython

提到了,全局变量在Flask中,好像不是线程安全的

-》对于此问题,有空再去深究吧。

Understanding Contexts in Flask

python – Preserving global state in a flask application – Stack Overflow

python – Flask global variables – Stack Overflow

转载请注明:在路上 » 【已解决】Flask中的全局变量的值获取不到

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
99 queries in 0.210 seconds, using 23.35MB memory