使用烧瓶中的全局变量(flask.g)

时间:2014-06-16 21:47:03

标签: python flask

我想在服务器上启动数据加载过程,这需要10-15分钟。 当该进程正在运行时,我想对服务器进行连续的ajax调用,以告诉用户数据加载过程在哪里。

我有一切工作; dataload,ajax等...但我可以来回传递状态。我正在使用像这样的全局g变量:

此功能最初由客户端调用。同时客户端启动5秒轮询(我已用一个简单的时间循环替换了一些代码,使思考变得简单):

@app.route('/updatedb')
def updatedb():
    while True:
        g.songcounter = time.strftime("%I:%M:%S")
        print(g.songcounter)
        time.sleep(1)
    models.add_collection("/media/store/Music")
    return 

客户端每隔5秒调用一次:

@app.route('/dbstatus')
def dbstatus():
    if g.songcounter:
        print("status:%s" % g.songcounter)
    else:
        print("status: no")
    k = g.songcounter #time.strftime("%I:%M:%S")
    return render_template("dbstatus.html", timestamp=k)

......这就是我得到的。 g.songcounter在更新线程之外无效... 这可能是公平的......但我该怎么办?

127.0.0.1 - - [17/Jun/2014 07:41:31] "GET /dbstatus HTTP/1.1" 500 -
07:41:31
07:41:32
127.0.0.1 - - [17/Jun/2014 07:41:33] "GET /dbstatus HTTP/1.1" 500 -
07:41:33
127.0.0.1 - - [17/Jun/2014 07:41:34] "GET /dbstatus HTTP/1.1" 500 -
07:41:34
07:41:35
127.0.0.1 - - [17/Jun/2014 07:41:36] "GET /dbstatus HTTP/1.1" 500 -
07:41:36
07:41:37
127.0.0.1 - - [17/Jun/2014 07:41:38] "GET /dbstatus HTTP/1.1" 500 -
07:41:38
127.0.0.1 - - [17/Jun/2014 07:41:39] "GET /dbstatus HTTP/1.1" 500 -
07:41:39

1 个答案:

答案 0 :(得分:2)

您不能将上下文对象设为g。上下文对象仅对一个线程有效,并在进入或退出后更改(例如,启动请求或结束请求)。有关详细信息,请参阅http://flask.pocoo.org/docs/appcontext/http://flask.pocoo.org/docs/reqcontext/或其他有趣的问题What is the purpose of Flask's context stacks?

因此,对于您来说,最好使用另一个共享存储用户/会话ID作为密钥:

  • 全球dict
  • 服务器端会话
  • cache / redis / memcacehd
  • 数据库
相关问题