Expire session in flask in ajax context

£可爱£侵袭症+ 提交于 2021-02-10 03:27:31

问题


I am using permanent_session_lifetime to expire the session of the user after some period of inactivity. The problem is that, this request is made through ajax, so i can't redirect in ajax context with the normal behavior of the flask.

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

Instead of this, I want to redirect to my logout route in the before_request, if the flask session expire. How can i do that?


@mod.before_request
def make_session_permanent(): 
    session.modified = True
    session.permanent = True
    app.permanent_session_lifetime = timedelta(minutes=10)

@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'))

回答1:


If you want to use the before_request approach, then check for the session's validity there and return a redirect as needed:

@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

Otherwise, swehren's comment is a good idea - instead of relying on the background to redirect the next call, have the Ajax call in the front redirect based on the return valid of the Ajax call:

$.ajax({
    type: "POST",
    url: "{{ url_for('login') }}",
    success: function(data) {
        // redirect if the data contained a qualifier for an expired session
    }
});


来源:https://stackoverflow.com/questions/30354765/expire-session-in-flask-in-ajax-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!