Invalidate an old session in Flask

后端 未结 4 1765
名媛妹妹
名媛妹妹 2020-12-13 10:29

How do I create a new clean session and invalidate the current one in Flask?

Do I use make_null_session() or open_session()?

4条回答
  •  隐瞒了意图╮
    2020-12-13 10:56

    You can add an after_request callback to remove the session cookie if a particular flag is set:

    @app.after_request
    def remove_if_invalid(response):
        if "__invalidate__" in session:
            response.delete_cookie(app.session_cookie_name)
        return response
    

    Then you simply set that session key whenever you want to invalidate the session:

    @app.route("/logout")
    def logout():
        session["__invalidate__"] = True
        return redirect(url_for("index"))
    

    See also: http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.BaseResponse.delete_cookie

提交回复
热议问题