Flask – Sessions

In contrast to a Cookie, Session data is put away on server. Session is the time interim when a client logs into a server and logs out of it. The data, which is should have been held over this session, is put away in an temporary directory on the server. A session with every client is alloted a Session ID. The Session data is put away over cookies and the server signs them cryptographically. For this encryption, a Flask application needs a characterized SECRET_KEY.

Session article is likewise a word reference item containing key-esteem sets of session factors and related values.

For example, to set a 'username' session variable utilize the statement −

Session[‘username’] = ’admin’

To release a session variable use pop() method.

session.pop('username', None)

The following code is a simple demonstration of session works in Flask. URL ‘/’ simply prompts user to log in, as session variable ‘username’ is not set.

def index():
   if 'username' in session:
      username = session['username']
         return 'Logged in as ' + username + '<br>' + \
         "<b><a href = '/logout'>click here to log out</a></b>"
   return "You are not logged in <br><a href = '/login'></b>" + \
      "click here to log in</b></a>"

As client browses to '/login' the login() view function, since it is called through GET method, opens up a login form.

A Form is posted back on '/login' and now session variable is set. Application is redirected to '/'. This time session variable 'username' is found.

@app.route('/login', methods = ['GET', 'POST'])
def login():   if request.method == 'POST':      session['username'] = request.form['username']
      return redirect(url_for('index'))
   return '''
   <form action = "" method = "post">
      <p><input type = text name = username/></p>
      <p<<input type = submit value = Login/></p>

The application also contains a logout() view function, which pops out ‘username’ session variable. Hence, ‘/’ URL again shows the opening page.

def logout():
   # remove the username from the session if it is there
   session.pop('username', None)
   return redirect(url_for('index'))

Run the application and visit the homepage. (Ensure to set secret_key of the application)

from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
app.secret_key = 'any random string’

The output will be displayed as shown below. Click the link “click here to log in”.