Bootstrap FreeKB - Flask - Modify a session
Flask - Modify a session

Updated:   |  Flask articles

This assumes you are already familiar with Flask Sessions. If not, check out my article FreeKB - Flask - Getting Started with Sessions.

Let's say you create a session with the "foo" key and a value of "bar".

from flask import render_template, session

@views.route('/')
def home():    
    session["greeting"] = "Hello"
    return render_template('home.html')

 

When hitting the / endpoint in this example, a signed cookie named "session" will be created in the users browser. Notice Content is a base 64 string.

 

On a Linux system, the base64 command may be able to decode the Content, which shows the key/value pair greeting: Hello.

~]$ echo eyJfcGVybWFuZW50Ijp0cnVlLCJmb28iOiJiYXIifQ.ZmbgnQ.jshPC47rtX5IxPhSh98UNkMVggA | base64 --decode
{"greeting":"Hello"}base64: invalid input

 

append can be used to modify a session. In this example, "World" is appended to the "greeting" session.

from flask import render_template, session

@views.route('/')
def home():    
    session["greeting"] = "Hello"
    return render_template('home.html')
    
@views.route('/Stage')
def Stage():    
    session['greeting'].append(' World')
    return render_template('stage.html')    

 

You may want to also set SESSION_MODIFIED to True in __init__.py to ensure that the session can be modified.

from flask import Flask

def myapp():
    app = Flask(__name__)
    
    app.config['SESSION_MODIFIED'] = True
    
    return app

 

Or using session.modified in one of your blueprint views.

from flask import render_template, session

session.modified = True

@views.route('/')
def home():    
    session["greeting"] = "Hello"
    return render_template('home.html')
    
@views.route('/Stage')
def Stage():    
    session['greeting'].append(' World')
    return render_template('stage.html')    

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 4deaf6 in the box below so that we can be sure you are a human.