Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.
- Model -> models.py
- View -> views.py
- Controller -> __init__.py
Flask Sessions and Flask Cookies are similar, the primary difference being
- Flask Sessions are encrypted
- Flask Cookies are not encrypted
Let's say your Flask app has the following structure.
├── main.py
├── my-project (directory)
│ ├── __init__.py
│ ├── views.py
│ ├── templates (directory)
│ │ ├── base.html
│ │ ├── home.html
│ │ ├── foo.html
│ │ ├── bar.html
Here is the syntax to create a session key value pair.
session['key'] = "value"
For example.
session['greeting'] = "Hello World"
In your controller (__init__,py in this example), set a SECRET_KEY, which is used to "salt" the session cookie.
from flask import Flask
def myapp():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'some_unique_string_of_data'
# VIEWS
from .views import views
app.register_blueprint(views, url_prefix='/')
return app
In your view (views.py in this example), import session, and create a session key value pair.
from flask import render_template, session
@views.route('/')
def home():
session["foo"] = "bar"
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. The SECRET_KEY is used to "salt" the string.
On a Linux system, the base64 command may be able to decode the Content, which shows the key/value pair foo/bar.
~]$ echo eyJfcGVybWFuZW50Ijp0cnVlLCJmb28iOiJiYXIifQ.ZmbgnQ.jshPC47rtX5IxPhSh98UNkMVggA | base64 --decode
{"foo":"bar"}base64: invalid input
There are two ways to get a session key value pair in Python.
- session['key']
- session.get('key')
So, how are these different?
Here is how you can print the value of a session in Python.
from flask import render_template, session
@views.route('/')
def home():
session['greeting'] = "Hello World"
print(session['greeting'])
return render_template('home.html')
Here is how you could use the session value in HTML.
{% extends "base.html" %}
{% block content %}
{% if session.greeting %}
session.greeting contains a value of {{ session.greeting }}
{% else %}
session.greeting does not exist
{% endif %}
{% endblock %}
Of course, you are almost always going to want to determine if a session key exists.
from flask import render_template, session
@blueprint.route('/foo')
def foo():
logger(f"This is the beginning of the 'foo' function")
session['greeting'] = "Hello World"
print(f"session['greeting'] in the foo function = {session['greeting']}")
return render_template('home.html')
@blueprint.route('/bar')
def bar():
logger(f"This is the beginning of the 'bar' function")
try:
session['greeting']
except KeyError:
print("got KeyError which suggests session['greeting'] does not exist")
else:
print(f"session['greeting'] in the bar function = {session['greeting']}")
return render_template('home.html')
And here is how you can do something based on the value of a session key in Python.
@views.route('/test')
def test():
try:
session.get('greeting')
except KeyError:
return "session.get('greeting') raised KeyError"
else:
print(f"session greeting= {session.get('greeting'}")
if session.get('greeting') == 'Hello World':
return "session greeting equals Hello World"
else:
return "session greeting does not equal bar"
Or, as a bit of a more practical example, here is how you could create a session when a user signs in, and clear sessions when a user signs out.
from flask import render_template, session
@views.route('/signin')
def signin():
session["signedin"] = True
return render_template('home.html')
@views.route('/signout')
def signout():
session.clear()
return render_template('home.html')
By default, sessions are set as permanent.
- Permanent session: A cookie is stored in the browser and not deleted until it expires.
- Non-permanent session: A cookie is stored in the browser and is deleted when the browser or tab is closed.
PERMANENT_SESSION_LIFETIME can be set in __init__.py. The session will expire when PERMANENT_SESSION_LIFETIME has been reached. In this example, the session lifetime is 14400 seconds (4 hours).
SESSION_PERMANENT can be set in __init__.py if you want every session created by your app to be permanent (True) or non-permanent (False).
from flask import Flask
def myapp():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'some_unique_string_of_data'
app.config['PERMANENT_SESSION_LIFETIME'] = 14400
app.config['SESSION_PERMANENT'] = True
# VIEWS
from .views import views
app.register_blueprint(views, url_prefix='/')
return app
session.permanent can be used to set a specific session as permanent or non-permanent. This will take precedence (override) SESSION_PERMANENT in __init__.py.
from flask import render_template, session
@views.route('/')
def home():
session.permanent = False
session["foo"] = "bar"
return render_template('home.html')
Did you find this article helpful?
If so, consider buying me a coffee over at