Flask永久会话:在哪里定义它们?

问题描述 投票:17回答:3

默认情况下,Flask使用volatile会话,这意味着会话cookie设置为在浏览器关闭时过期。为了使用永久会话,它将使用具有定义的到期日期的cookie,应该设置session.permanent = Truementioned in this question.,并且将根据config['PERMANENT_SESSION_LIFETIME']设置到期日期。

我很惊讶会话生存期在配置文件中定义,但是不可能通过配置请求使用永久会话,例如config['USE_PERMANENT_SESSION'] = True。但就是这样吧。

我的问题是:如果你确实想要永久性会议,那么定义它们的最佳位置是什么?它是否在上述问题中提出的@app.before_request函数中?但是这意味着每次请求都会重新设置它?似乎一旦确定,session.permanent仍然是真的,直到会议结束。

永久会话通常在登录后使用,所以在处理login_user()时,请求它们的最佳位置可能?那么对所有匿名页面使用易失性会话cookie的最佳策略是什么,并通过在登录时执行session.permanent = True切换到永久会话?

人们可能希望根据它是普通的session cookie还是remember_me cookie来设置不同的生命周期。实现这一目标的最佳方法是什么?

python session cookies flask flask-login
3个回答
15
投票

我很惊讶没有回答这个问题。似乎应该有某种类型的配置变量SESSION_PERMANENT = True。但不幸的是没有。正如您所说,这是最好的方法。

@app.before_request
def make_session_permanent():
    session.permanent = True

2
投票

我选择你说的“login_user()”

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

如果它设置为app.before_request,这将导致设置它们太多次。


1
投票

Should you use PERMANENT_SESSION_LIFETIME and session.permanent?

您实际想要做的可能是用户的登录状态到期。但是,此配置会使会话对象/ cookie过期,其中包含用户的登录状态以及(可能)存储在session中的其他一些数据。

Do you need to set session.permanent?

Flask's doc说:

Flask的默认cookie实现验证加密签名不​​早于此值。

session.permanentPERMANENT_SESSION_LIFETIME的附加组件。如果你没有将session.permanent设置为True,有时可以。

如果你没有设置session.permanent,会话cookie的生命周期不会受到PERMANENT_SESSION_LIFETIME的影响。但Flask将查看PERMANENT_SESSION_LIFETIME和会话cookie中的时间戳,以查看会话cookie是否仍然有效。如果时间戳太长于PERMANENT_SESSION_LIFETIME指定的时间戳,则会被忽略。但cookie仍然存在。

这就是Flask忽略会话cookie的方式:

def open_session(self, app, request):
    s = self.get_signing_serializer(app)
    if s is None:
        return None
    val = request.cookies.get(app.session_cookie_name)
    if not val:
        return self.session_class()
    max_age = total_seconds(app.permanent_session_lifetime)
    try:
        data = s.loads(val, max_age=max_age)
        return self.session_class(data)
    except BadSignature:
        return self.session_class()

如果设置session.permanent=True,验证仍将完成。而且,会话cookie将在PERMANENT_SESSION_LIFETIME之后过期并从浏览器中删除。

这就是PERMANENT_SESSION_LIFETIME如何控制cookie的过期:

def get_expiration_time(self, app, session):
    if session.permanent:
        return datetime.utcnow() + app.permanent_session_lifetime


def save_session(self, app, session, response):
    ...
    expires = self.get_expiration_time(app, session)
    val = self.get_signing_serializer(app).dumps(dict(session))
    response.set_cookie(
        app.session_cookie_name,
        val,
        expires=expires,
        httponly=httponly,
        domain=domain,
        path=path,
        secure=secure,
        samesite=samesite
    )

Do you need to set session.permanent for every request?

session.permanent默认是session['_permanent']。它的价值将留在session。但是,如果您仅在用户登录时分配,请通过检查用户如何绕过登录路线进行登录来保持警惕。例如,通过注册。

© www.soinside.com 2019 - 2024. All rights reserved.