I am using:

  • Python 3.6.1
  • Flask 0.12.2

Section on session of Flask documentation says that:

This is a proxy.

and section on proxies elaborates that:

Some of the objects provided by Flask are proxies to other objects. The reason behind this is that these proxies are shared between threads and they have to dispatch to the actual object bound to a thread behind the scenes as necessary.
...
If you need to get access to the underlying object that is proxied, you can use the _get_current_object() method

This all is pretty much straightforward.
But when I try the following:

from flask import (
Flask,
session,
)

app = Flask(__name__)
app.secret_key = 'some random secret key'

@app.route('/')
def index():
    print("session ID is: {}".format(id(session)))
    print("session._get_current_object() ID is: {}".format(id(session._get_current_object())))
    print('________________________________')

    return 'Check the console! ;-)'

each time I make a request to / — the value of id(session._get_current_object()) is different, while id(session) remains the same.

Following Flask documentation, quoted above, it should be the other way around. So why is this happening?


UPDATE
inspired by brunns's suggestion in the comments to his answer, that there is one underlying object per thread

Here is some code, to test assumption that there is one underlying session object (session._get_current_object()) per thread:

import threading

from flask import (
Flask,
session,
)

app = Flask(__name__)
app.secret_key = 'some random secret key'

@app.route('/')
def index():
    print("session ID is: {}".format(id(session)))
    print("session._get_current_object() ID is: {}".format(id(session._get_current_object())))
    print("threading.current_thread().ident is: {}".format(threading.current_thread().ident))
    print('________________________________')
    return 'Check the console! ;-)'

Despite the expectations, threading.current_thread().ident) is never changed, while is id(session._get_current_object() is changing.

1 Answers

2
brunns On Best Solutions

session is an object you have imported from the flask module. You only import it once, and it doesn't change, so nor will its id(). It's shared between threads, and it's a proxy to the underlying objects.

Each request may be run on a different thread, and each will have a different underlying object, so they may have different id()s.