首页 > 解决方案 > Flask 会话 Cookie 过期

问题描述

我正在尝试将 cookie 的过期时间设置为比浏览器会话长。我config.py的是:

from datetime import timedelta
SESSION_FILE_DIR = 'C:/some/path15'
SECRET_KEY= 'abcdefg'
DEBUG = True
SESSION_PERMANENT = True
PERMANENT_SESSION_LIFETIME = timedelta(days=30)

然后为了模仿这个例子的应用程序结构,我有一个注册蓝图的主应用程序:

from flask import Flask, render_template, request, session, current_app
from flask_session import Session
import tempfile
 
server = Flask(__name__)
server.config.from_pyfile('config.py')

### Import and Register Blueprints 
from tools.routes import my_bp

server.register_blueprint(my_bp)

@server.route('/')
def homepage():
    return "Hello"
   
if __name__ == '__main__':
    server.run(debug=True)

然后一个蓝图叫做routes.py生活在主应用程序的子目录中,叫做tools

from flask import Flask, render_template, request, session, Blueprint, current_app
from flask_session import Session
import tempfile

my_bp = Blueprint("my_bp", __name__)

@my_bp.route('/new', methods=['POST', 'GET'])
def path(): 
    if 'path' not in session: ##new
        session['path'] = tempfile.mkdtemp() ##new
    path = session['path'] ##new
    return path

运行此应用程序时(通过 /new 路由),如果我在浏览器中检查存储下的元素,则显示 cookie expire/max_age 为Session.

我怎样才能让这个尊重我在config.py文件中设置的 30 天到期?

标签: pythonpython-3.xflasksession-cookies

解决方案


from flask import session, app
@app.before_request
def before_request():
    session.permanent = True
    app.permanent_session_lifetime = datetime.timedelta(minutes=20) # session will be alive for 20 minutes
    

推荐阅读