python - 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 天到期?
解决方案
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
推荐阅读
- django - 即使在我的 Django 管理页面中也没有加载静态文件
- c++ - #import "msado15.dll" C++ 在现有项目中
- excel - 命名范围数组不起作用或不可能?
- c# - 匿名方法应按条件返回字符串
- go - 仅知道接口时克隆结构
- java - JBOSS 服务器抛出异常 - 无法转换为 org.apache.xml.dtm.DTMManager
- uwp - UserControl 中的绑定问题
- c++ - 最后的每一个组合都是双重基本 C++
- mysql - 为什么 innodb 缓冲池内存在命令“优化表”后会增长?
- node.js - 我无法运行我的节点服务器 Babel 编译错误