我正在学习烧瓶,并且正在尝试将一些随机生成的数据与每个会话相关联。 我使用this answer中的方法将session.permanent设置为False,但是关闭浏览器,然后在返回页面时重新打开它仍显示相同的代码。
MWE:
from flask import Flask, session
import numpy as np
app = Flask(__name__)
app.secret_key = "supersecretkey"
@app.before_request
def make_session_permanent():
session.permanent = False
@app.route('/')
def index():
if 'id' not in session:
random_id = "".join(np.random.choice(list("abcdefg123"), 16))
session["id"] = random_id
return session['id']
if __name__ == '__main__':
app.run(debug=True)
更新:基于this answer,有人建议使用socketio注意到断开连接。这也没有什么区别,即关闭浏览器,然后重新打开,然后转到127.0.0.1:5000,该数字与关闭前的数字相同。使用此更新的MWE如下:
from flask import Flask, session
from flask_socketio import SocketIO
import numpy as np
app = Flask(__name__)
app.secret_key = "supersecretkey"
@app.before_request
def make_session_permanent():
session.permanent = False
@app.route('/')
def index():
if 'id' not in session:
random_id = "".join(np.random.choice(list("abcdefg123"), 16))
session["id"] = random_id
return session['id']
socketio = SocketIO(app)
@socketio.on('disconnect')
def disconnect_user():
session.pop('id', None)
if __name__ == '__main__':
app.run(debug=True)
答案 0 :(得分:0)
# Instantiate a new web application called `app`,
# with `__name__` representing the current file
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False