关于python:在ajax上下文中的flask中过期会话 | 珊瑚贝

Expire session in flask in ajax context


我正在使用 permanent_session_lifetime 在一段时间不活动后使用户的会话到期。问题是,这个请求是通过 ajax 发出的,所以我不能用Flask的正常行为在 ajax 上下文中重定向。

1
http://xxxx/login?next=%2Fusers%2Fajax_step1

如果Flask会话到期,我想在 before_request 中重定向到我的 logout 路由,而不是这个。我该怎么做?

1
2
3
4
5
@mod.before_request
def make_session_permanent():
    session.modified = True
    session.permanent = True
    app.permanent_session_lifetime = timedelta(minutes=10)
1
2
3
4
5
6
7
@mod.route(‘/logout’)
@login_required
def logout():
    logout_user()
    session.clear()
    flash(gettext(u‘You have been logged out.’))
    return redirect(url_for(‘auth.login’))
  • 您能否修改您的 AJAX 以查找一些注销指示(可能是状态代码,或使用 JSON 消息),然后将其重定向到正确的页面?


如果您想使用 before_request 方法,请在此处检查会话的有效性并根据需要返回重定向:

1
2
3
4
5
6
7
@mod.before_request
def make_session_permanent():
    if session_is_invalid(session):
        return redirect(url_for(‘logout’))

def session_is_invalid(ses):
    # return your qualifier

否则,swehren 的注释是个好主意——不要依赖后台重定向下一个调用,而是根据 Ajax 调用的返回有效在前面重定向 Ajax 调用:

1
2
3
4
5
6
7
$.ajax({
    type:“POST”,
    url:“{{ url_for(‘login’) }}”,
    success: function(data) {
        // redirect if the data contained a qualifier for an expired session
    }
});

来源:https://www.codenong.com/30354765/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9179.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?