English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Unlike cookies, session data is stored on the server. A session is the time interval during which a client logs into the server and logs out. The data to be stored in this session is stored in a temporary directory on the server.
Assign a session ID to each client's session. Session data is stored at the top of the cookie, and the server signs it in an encrypted manner. For this encryption, the Flask application needs a defined SECRET_KEY.
The session object is also a dictionary object containing key-value pairs of session variables and associated values.
For example, to set the 'username' session variable, use the statement -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 Session['username'] = 'admin'
To delete a session variable, please use the pop() method.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 session.pop('username', None)
The following code is a simple demonstration of how sessions work in Flask. URL => '/' Prompt the user to log in because the session variable username is not set.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 @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</">/b>" return "You are not logged in\n<a href="/login'>/b>" + \ "click here to log in"/b></a>"
When the user navigates to URL=>'/login' when the login() function displays the view, because it is called via the GET method, so a login form is opened.
The form is resubmitted to URL=> /login, the session variable is now set. The application is redirected to URL=> /. At this point, find the session variable: username.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 @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 application also includes a logout() view function that deletes the value of the 'username' session variable. The URL is redirected to '/‘ Display the start page.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 @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 application and access the homepage (make sure to set the application's secret_key).
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) app.secret_key = 'any random string'
The complete code is shown as follows -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 from flask import Flask from flask import render_template from flask import request from flask import make_response from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) app.secret_key = 'fkdjsafjdkfdlkjfadskjfadskljdsfklj' @app.route('/) def index(): if 'username' in session: username = session['username'] return 'The login username is:' + username + "<br>" + \ "<b><a href="/logout'>Click here to log out</">/b>" return "You are not logged in,\n<a href="/login'>/b>" + \ "Click here to log in</b></a>" @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> ''' @app.route('/logout') def logout(): # remove the username from the session if it is there session.pop('username', None) return redirect(url_for('index')) if __name__ == '__main__': app.run(debug=True)
The output will be displayed as follows. Click the link “ Click here to log in”
The link will be redirected to another interface. Enter ‘admin’.
The screen will display the message “ The login username is: adminAs shown below -