Sessions in Flask explained & why are they important?
In this part of the flask tutorial, we are going to learn about sessions in flask. We are also going to learn why are they essential for any web page and how to implement them on our web page. In this tutorial, we are going to learn about sessions in flask.
Flask – Sessions
The concept of a session is no different from that of a cookie; it’s just that the data in a session is saved on the server rather than on your local machine. The duration for which a user logs into the server and logs out can be defined as the session. The data used to track the session of a user is usually stored in a temporary directory on the user’s system.
Each session with a client is assigned a Session ID. The session data is signed by the server cryptographically and is stored on top of the cookies. So, for this type of encryption, a flask webpage needs a SECRET_KEY. We can hard code the secret key in our flask code or else we can store the SECRET_KEY in an environment variable into our local machine.
Just like cookies, sessions are also saved as dictionary objects containing key-value pairs of session variables and their values.
Example of a session –
To create a session variable called ‘username,’ we can write the following statement –
Session[‘username’] = ’guest’
To delete the session, we can use the pop() command.
Session in Flask – example
The following code is an example of how sessions work in a flask webpage. The URL ‘/‘ prompts the user to sign in; this happens because the session variable is not set in this URL.
@app.route('/') 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. Please log in first! <br><a href = '/login'></b>" + \ "Log in here</b></a>"
A login form opens up when the user visits the ‘/login‘ URL. This login form opens up is opened because of the login() view function is called through the GET method.
This form is then returned back to the ‘/login‘ URL, which then results in the setting up of the session variable. After this, the page is redirected back to the ‘/‘ URL. Then the time session variable ‘username‘ is being 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> </form> '''
The code also contains a ‘logout()‘ function which is used to delete the current session. This results in the ‘/‘ URL once again showing the opening page.
@app.route('/logout') def logout(): # remove the username from the session if it is there session.pop('username', None) return redirect(url_for('index'))
Run the flask application and make sure to set the SECRET_KEY. You can set it by –
from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) app.secret_key = 'any random string’
Leave a Reply