0

My understanding is that flask.g object or flask.request are the thread local storage. However when I execute the following code, it shows the id of flask.g (and flask.request) is always same value in each threads:

from flask import Flask, request, g
app = Flask(__name__)

@app.route('/')
def hello():
    print("g id: %d" % id(g))
    print("request id: %d" % id(request))
    return "Hello world"

if __name__ == "__main__":
    app.run()

result (access three times with several browsers):

g id: 140219657264584
request id: 140219657262640
g id: 140219657264584
request id: 140219657262640
g id: 140219657264584
request id: 140219657262640

My understanding iswrong?

  • 1
    By default, flask only use one thread, so every request you sent are hitting that same one thread. Now if you [add a background thread](https://stackoverflow.com/questions/14384739/how-can-i-add-a-background-thread-to-flask#22900255) things will be different (also please refer to that question's related question on the sidebar). – metatoaster Nov 16 '18 at 02:11
  • They are proxy objects for convenient access to thread-local variables. – Klaus D. Nov 16 '18 at 03:36

1 Answers1

0

I think g and request is the variable object.So the id will always equal.

When in g to set data

g = {}
g[current thread id] = your data

When in g to get data

g[current thread id]

So flask.g and flask.request are thread local storage

jiangyx3915
  • 119
  • 3
  • Thank you for your answer. I understand g is global variable itself. However I can put stuff in it and can get back later from the one in a thread-safe. The following doc says that: [http://werkzeug.pocoo.org/docs/0.14/local/](http://werkzeug.pocoo.org/docs/0.14/local/) – ryo.fastriver Nov 16 '18 at 04:25