繁体   English   中英

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

[英]Using the global variable in flask (flask.g)

我想在服务器上启动数据加载过程,这需要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

您不能将上下文对象用作g 上下文对象仅对一个线程有效,并在进入或退出后更改(例如,启动请求或结束请求)。 有关详细信息,你可以阅读http://flask.pocoo.org/docs/appcontext/http://flask.pocoo.org/docs/reqcontext/或另一个有趣的问题是什么瓶的上下文的目的栈?

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

  • 全球dict
  • 服务器端会话
  • cache / redis / memcacehd
  • 数据库
  • 等等

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM