是否有一种简单的方法使会议在烧瓶超时?

我正在建立一个网站与烧瓶用户有帐户,并能够登录。 我使用烧瓶主体部分日志和角色管理。 有没有办法让用户的会话在5分钟或10分钟后过期? 我在烧瓶文档或者烧瓶校长的文档中找不到这些。

我想到了一种手工操作的方法,在登录时设置一个带有时间标记的可变服务器端,在用户采取下一个操作时,服务器验证时间戳上的时间差并删除会话。

109153 次浏览

flask sessions expire once you close the browser unless you have a permanent session. You can possibly try the following:

from datetime import timedelta
from flask import session, app


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

By default in Flask, permanent_session_lifetime is set to 31 days.

Yes, We should set

session.permanent = True
app.permanent_session_lifetime = timedelta(minutes=5)

But I don't think it should be set at app.before_request, This will lead to set them too may times.

The permanent_session_lifetime is a Basics Configuration, so it should be set at you configure the app:

 from datetime import timedelta
app = Flask(__name__)
app.config['SECRET_KEY'] = 'xxxxxxxxx'
app.config['PERMANENT_SESSION_LIFETIME'] =  timedelta(minutes=5)

The session will created for each client, seperated from other clients. So, I think the best place to set session.permanent is when you login():

@app.route('/login', methods=['GET', 'POST'])
def login():
#After Verify the validity of username and password
session.permanent = True

Using a slight modification on CodeGeek's answer, the decorator @before_first_request is enough to get flask to "remember" the session timeout. @before_request runs before EACH request, which is not necessary. I've tested this with different timeouts and it works.

The calls are explained here.

from datetime import timedelta
from flask import session, app


@app.before_first_request  # runs before FIRST request (only once)
def make_session_permanent():
session.permanent = True
app.permanent_session_lifetime = timedelta(minutes=5)