Open In App

session._get_current_object() in Flask

The session._get_current_object() method returns a session object for the current request that is made. It stores the information on the client’s computer as it works on the client side.

The exact object returned by the session._get_current_object() method completely depends on the implementation of the session so in the flask the method returns an instance of the ‘secureCookieSession’ class which is a subclass of the ‘dict’ which is a python built-in type.



Let’s understand session._get_current_object() : 

Using session._get_current_object()

Example:






from flask import Flask, session
  
# initialize Flask app
app = Flask(__name__)
  
# set secret key for session
app.secret_key = "secret_key"
  
# route to set a value in the session dictionary
@app.route('/set_session')
def set_session():
    current_session = session._get_current_object()
    current_session['username'] = 'GeekforGeeks'
    current_session['logged_in'] = True
    return 'Session variables set'
  
# route to get a value from the session dictionary
@app.route('/get_session')
def get_session():
    current_session = session._get_current_object()
    username = current_session.get('username', 'Guest')
    logged_in = current_session.get('logged_in', False)
    return f'Username: {username}, Logged in: {logged_in}'
  
# start Flask app
if __name__ == '__main__':
    app.run(debug=True)

Now all done to run flask project type in command: 

python <file-name>.py

Now navigate to the /set_session route, the session variables username and logged_in will be set in the session dictionary and the output screen will be like: 

Output:

Setting the variables in session

output of the code

This output indicates that the session dictionary now contains two keys, ‘username’ and ‘logged_in’, with the value of ‘logged_in’ set to True.

In the output generated, we can see that session. get current object() doesn’t really return a dictionary-type result. It is an instance of the Python dict type, which was actually covered, as it’s a subclass of the SecureCookieSession class.

A SecureCookieSession object can behave like a dictionary in many ways, that way you can still access the data stored in the session object as if it were a dictionary by using the familiar dictionary syntax.


Article Tags :