Welcome to our comprehensive guide on Session Management in Flask! This tutorial is designed to help both beginners and intermediates understand and implement session management in their Flask applications.
Session Management is a mechanism that allows a web application to maintain state information about a user across multiple requests. This is particularly useful for applications where user authentication, shopping carts, or other stateful information needs to be preserved between requests.
Cookies are not secure for storing sensitive data like passwords, and they have size limitations. Sessions, on the other hand, are stored on the server, making them more secure and suitable for storing sensitive data.
Flask provides a simple and easy-to-use session management system out of the box. Let's dive into how to use it.
To create a session, you simply use the session dictionary that Flask provides. Here's an example:
from flask import Flask, session
app = Flask(__name__)
@app.route('/create_session')
def create_session():
# Set a session value
session['key'] = 'value'
return 'Session created!'In this example, we've created a new Flask application and defined a route that sets a key-value pair in the session.
To access a session, you can simply retrieve the value using the session dictionary:
@app.route('/get_session')
def get_session():
return f'Session Key: {session.get('key', 'Not Found')}'In this example, we've defined another route that retrieves the value of the 'key' from the session.
To delete a session, you can use the clear() method:
@app.route('/delete_session')
def delete_session():
# Delete session
session.clear()
return 'Session deleted!'In this example, we've defined a route that deletes the entire session.
Which method is used to delete a session in Flask?
Let's create a simple user login system where a user logs in and we store their username in the session.
from flask import Flask, session, render_template, request, redirect
app = Flask(__name__)
# Sample user data
USERS = {'john': 'password1', 'jane': 'password2'}
@app.route('/')
def login():
return render_template('login.html')
@app.route('/login', methods=['POST'])
def login_user():
username = request.form.get('username')
password = request.form.get('password')
if username in USERS and USERS[username] == password:
# Login successful, store username in session
session['username'] = username
return redirect('/welcome')
else:
# Login failed
return 'Invalid credentials'
@app.route('/welcome')
def welcome_user():
if 'username' not in session:
return redirect('/')
username = session['username']
return f'Welcome, {username}!'
@app.route('/logout')
def logout_user():
# Logout, delete username from session
session.clear()
return redirect('/')In this example, we've created a simple Flask application that includes a login form, a welcome page, and a logout button. When a user logs in with valid credentials, their username is stored in the session, and they are redirected to the welcome page. When they log out, the session is deleted.
And that's it! You now have a good understanding of session management in Flask. Happy coding! 🚀