How to set the session expiration time in Flask?
In Flask, the expiration time of a session can be set by adjusting the PERMANENT_SESSION_LIFETIME parameter. By default, sessions expire immediately after the browser is closed, but this time can be changed through configuration.
Here are the steps to set the session timeout.
- In a Flask application, locate the configuration file (typically config.py or app.py).
- Add the following code to the configuration file to set the session expiration time:
# 设置session的过期时间为30分钟
PERMANENT_SESSION_LIFETIME = timedelta(minutes=30)
- The permanent session
from flask import session
@app.route('/login', methods=['POST'])
def login():
# 登录成功后,设置session为永久性
session['username'] = 'admin'
session.permanent = True
return 'Login Success'
By setting the PERMANENT_SESSION_LIFETIME parameter and using the session.permanent attribute, you can specify the expiration time of Flask’s session. Keep in mind that the value of the PERMANENT_SESSION_LIFETIME parameter is a timedelta object and can be adjusted to different time intervals as needed.