Flask Session –
- Flask-Session is an extension for Flask that support Server-side Session to your application.
- The Session is the time between the client logs in to the server and logs out of the server.
- The data that is required to be saved in the Session is stored in a temporary directory on the server.
- The data in the Session stored on the top of cookies and signed by the server cryptographically.
- Each client will have their own session there own data will be store in their session.
Uses of Session
- Remember user when they log in
- Store User specific website settings (theme)
- Store E-Commerce site user items in cart
This article assumes you are familiar with flask basics. Checkout – Flask – (Creating first simple application) to learn how to make a simple web application in flask.
Installation
Install the extension with the following command
$ easy_install Flask-Session
Alternatively, if you have pip installed
$ pip install Flask-Session
Configuring Session in Flask
- The Session instance is not used for direct access, you should always use flask_session.
- The First line (session) from the flask is in such a way that each of us as a user gets our own version of the session.
Python3
from flask import Flask, render_template, redirect, request, session
from flask_session import Session
|
This specific to the flask_session library only
- SESSION_PERMANENT = False – So this session has a default time limit of some number of minutes or hours or days after which it will expire.
- SESSION_TYPE = “filesystem” – It will store in the hard drive (these files are stored under a /flask_session folder in your config directory.) or any online ide account and it is an alternative to using a Database or something else like that.
Python3
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
|
Remember User After Login
So we will start making two basic pages and their route called index.html and login.html
- login.html contains a form in which the user can fill their name and submit
- index.html is the main page
Python3
@app.route("/")
def index():
return render_template('index.html')
@app.route("/login", methods=["POST", "GET"])
def login():
return render_template("login.html")
|
- We need to record the username in the session when they submit the form
- And we are using a dictionary in python where “name” is the key = request.form.get(“name”) is a value
Python3
@app.route("/login", methods=["POST", "GET"])
def login():
if request.method == "POST":
session["name"] = request.form.get("name")
return redirect("/")
return render_template("login.html")
|
- After storing the user name we need to check whenever user lands on the index page that any session with that user name exists or not.
- If the user name doesn’t exist then redirect to the login page.
Python3
@app.route("/")
def index():
if not session.get("name"):
return redirect("/login")
return render_template('index.html')
|
- After successfully remember the user we also need a way to logout the users.
- So whenever the user clicks logout change the user value to none and redirect them to the index page.
Python3
@app.route("/logout")
def logout():
session["name"] = None
return redirect("/")
|
Complete Project –
Python3
from flask import Flask, render_template, redirect, request, session
from flask_session import Session
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
@app.route("/")
def index():
if not session.get("name"):
return redirect("/login")
return render_template('index.html')
@app.route("/login", methods=["POST", "GET"])
def login():
if request.method == "POST":
session["name"] = request.form.get("name")
return redirect("/")
return render_template("login.html")
@app.route("/logout")
def logout():
session["name"] = None
return redirect("/")
if __name__ == "__main__":
app.run(debug=True)
|
index.html
- We can also use session.name to excess the value from the session.
HTML
{% extends "layout.html" %}
{% block y %}
{% if session.name %}
You are Register {{ session.name }} <a href="/logout">logout</a>.
{% else %}
You are not Register. <a href="/login">login</a>.
{% endif %}
{% endblock %}
|
login.html
HTML
{% extends "layout.html" %}
{% block y %}
<h1> REGISTER </h1>
<form action="/login" method="POST">
<input placeholder="Name" autocomplete="off" type="text" name="name">
<input type="submit" name="Register">
</form>
{% endblock %}
|
layout.html
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="initial-scale=1, width=device-width">
<title> flask </title>
</head>
<body>
{% block y %}{% endblock %}
</body>
</html>
|
Output –
login.html

index.html

You can also see your generated session


Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course