Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the global variable in flask (flask.g)

Tags:

python

flask

I want to start a data load process on the server which will take 10-15 minutes. While that process is running I want to make continuous ajax calls to the server to tell the user where the data load process is.

I have everything working; the dataload, the ajax, etc...But I can pass the status back and forth. I'm using the global g variable like this:

This function is initially called by the client. At the same time the client initiates the 5 sec polling (I have replaced some of the code with a simple time loop to make thinkes simple) :

@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 

This is what the client calls every 5 sec:

@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)

...and this is what I get. The g.songcounter is not valid outside the update thread... This may be fair enough...but what do I do?

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
like image 382
martin Avatar asked Aug 07 '26 09:08

martin


1 Answers

You can't do this with context objects as g. Context object live only for one thread and changed after going in or out (start request or end request for example). For details you can read http://flask.pocoo.org/docs/appcontext/, http://flask.pocoo.org/docs/reqcontext/ or another interesting question What is the purpose of Flask's context stacks?.

So for you case better use another shared storage user/session id as key:

  • global dict
  • server side session
  • cache / redis / memcacehd
  • database
  • etc
like image 178
tbicr Avatar answered Aug 09 '26 02:08

tbicr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!