我正在使用 Flask-Login 登录用户,并且希望能够在用户手动注销 Flask 应用程序之前关闭浏览器时注销用户(我想跟踪会话时间)。
这可以通过 Flask-SocketIO 来完成:
@socketio.on('disconnect')
def disconnect_user():
if current_user.is_authenticated:
logged_out = logout_user()
logger.debug('logged_out OK: {0}, current_user.is_authenticated: {1}'.format(logged_out, current_user.is_authenticated))
注意,您需要按照 SocketIO 的文档运行客户端 JS
关闭浏览器大约一分钟后,disconnect_user 方法运行并打印“logged_out OK: True, current_user.is_authenticated: False”。一切都很好,但是当我再次打开浏览器并按照下面调用 current_user.is_authenticated 时,它返回 True!
主页.html:
<ul class="nav navbar-nav">
{% if not current_user.is_authenticated %}
<li ><a href="{{ url_for('view.index') }}">Index</a></li>
{% else %}
<li><a href="{{ url_for('app.user_link') }}">User link</a></li>
{% endif %}
</ul>
对我来说似乎很奇怪 current_user.is_authenticated 显然是 False,然后为相同的服务器会话但不同的浏览器会话返回 True。知道发生了什么以及如何解决这个问题吗?
根据要求的登录名和用户模型代码:
@auth_view.route("/login", methods=["GET", "POST"])
def login():
if current_user is not None and current_user.is_authenticated:
flash("Already logged in.", 'info')
return redirect(url_for('main_view.index'))
form = LoginForm(request.form)
if form.validate_on_submit():
#find user in db then
login_user(user)
def User(Base):
id = Column(Integer, primary_key=True)
email = Column(String, unique=True)
name = Column(String(255))
#password code here
def get_id(self):
return str(self.id)
def is_active(self):
return self.active
def is_anonymous(self):
return False
def is_authenticated(self):
return True