Reading the documentation I understand that flask defines a class flask.session.
The thing that confuses me is that when people use it they don't instantiate an object of the session class, but use session directly, as in the following code:
from flask import Flask, session
app = Flask(__name__)
@app.route('/')
def index():
session['key'] = 'value'
I don't understand why the code shouldn't look something like this instead:
from flask import Flask, session
app = Flask(__name__)
s = session() # so s is an instance of the flask.session class
@app.route('/')
def index():
s['key'] = 'value'
I am also wondering if this has anything to do with session being a proxy, as it says in the documentation. I read the 'Notes on Proxies' but couldn't understand much.
Awesome question.
It gets initialized in flasks globals.py
https://github.com/pallets/flask/blob/master/flask/globals.py
session = LocalProxy(partial(_lookup_req_object, 'session'))
So when you import from flask you import from its package __init__.py
which pulls session from globals.py
and initializes it. You grab a reference to that when you directly import it.
I should clarify that session itself is not a class. It’s an instance of the LocalProxy class, which is a proxy to the request context.