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

Flask permanent session: where to define them?

默认情况下,Flask 使用易失性会话,这意味着会话 cookie 设置为在浏览器关闭时过期。为了使用永久会话,这将使用具有定义的到期日期的 cookie,应该设置 session.permanent = True,如 mentioned 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 来设置不同的生命周期。实现此目标的最佳方法是什么?

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

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

我选你说的"login_user()"

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

如果设置在app.before_request,这会导致设置太多次。

你应该使用 PERMANENT_SESSION_LIFETIMEsession.permanent 吗?

您真正想要做的可能是使用户的登录状态过期。但是,此配置会使会话 object/cookie 过期,其中包含用户的登录状态以及(可能)您存储在 session.

中的一些其他数据

是否需要设置session.permanent

根据Flask's doc

Flask’s default cookie implementation validates that the cryptographic signature is not older than this value.

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
    )

是否需要为每个请求设置 session.permanent

默认情况下

session.permanent 实际上是 session['_permanent']。它的值会留在session。 但是,如果您打算仅在用户登录时分配它,请通过检查用户如何绕过登录路径来登录来保持警惕。例如,通过注册。

正如@Hooloovoo13 在他对 Mikey 回复的评论中指出的那样(死 link),您可以使用 Flask-Session 扩展来完全控制您的 Flask 会话。它允许您在设置应用程序时配置 session-specific 参数:

from flask import Flask
from flask_session import Session


app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
Session(app) 

尽管上面的代码实际上毫无意义,因为 SESSION_PERMANENT 的 Flask-Session 扩展默认值是 True:

SESSION_PERMANENT | Whether use permanent session or not, default to be True only since the default value