What is the usage of flask session?
Flask Session is an extension provided by the Flask framework, used for managing user session data in a web application. It allows for storing and accessing information such as login status and shopping cart contents.
The steps for using the Flask Session extension are as follows:
- To install the Flask Session extension, you can use pip by running the command pip install flask-session.
- To import extensions in a Flask application, you can import Flask Session extension in the main file of the application, such as from flask_session import Session.
- Set up Flask Session: Add relevant configurations to the Flask application settings, such as specifying the session storage method and encryption key. For example:
app.config['SESSION_TYPE'] = 'redis' # session 存储方式为 Redis
app.config['SESSION_REDIS'] = redis.from_url('redis://localhost:6379') # Redis 服务器配置
app.config['SECRET_KEY'] = 'your_secret_key' # 加密密钥
- Initialize Flask Session: Initialize Flask Session on the application instance, such as Session(app).
- Using Flask Session: You can use the session object in the view function to store and retrieve user session data. For example:
from flask import session
@app.route('/login', methods=['POST'])
def login():
username = request.form['username']
password = request.form['password']
# 验证用户名和密码...
if valid_credentials(username, password):
session['logged_in'] = True
session['username'] = username
return redirect(url_for('dashboard'))
else:
return 'Invalid credentials', 401
@app.route('/dashboard')
def dashboard():
if session.get('logged_in'):
# 用户已登录,显示用户信息
username = session.get('username')
return f'Welcome, {username}!'
else:
# 用户未登录,跳转到登录页面
return redirect(url_for('login'))
The above is the basic usage of Flask Session, which makes it convenient to manage user session data and store or retrieve data in view functions using the session object. It is important to note that Flask Session defaults to storing session data in the server’s memory, but can also be configured to store it in a database or other storage methods for persistent storage.