pat*_*atb 18 python cookies session flask flask-login
默认情况下,Flask使用volatile会话,这意味着会话cookie设置为在浏览器关闭时过期.为了使用永久会话,这将使用具有已定义的到期日期的cookie,应该设置session.permanent = True,如本问题中所述.,将根据以下内容设置到期日期config['PERMANENT_SESSION_LIFETIME'].
我很惊讶会话生存期在配置文件中定义,但是无法通过配置请求使用永久会话,例如a config['USE_PERMANENT_SESSION'] = True.但就是这样吧.
我的问题是:如果你确实想要永久性会议,那么定义它们的最佳位置是什么?它是否@app.before_request在上述问题中提出的功能中?但是这意味着每次请求都会重新设置它?似乎一旦确定,session.permanent直到会议结束时仍然如此.
永久会话通常在登录后使用,因此请求处理时最好的地方是处理login_user()?那么对所有匿名页面使用易失性会话cookie的最佳策略是什么,并通过session.permanent = True登录切换到永久会话?
人们可能希望根据它是普通的sessioncookie还是remember_mecookie 来设置不同的生命周期.实现这一目标的最佳方法是什么?
小智 16
我很惊讶没有回答这个问题.似乎应该有某种类型的配置变量SESSION_PERMANENT = True.但不幸的是没有.正如您所说,这是最好的方法.
@app.before_request
def make_session_permanent():
session.permanent = True
Run Code Online (Sandbox Code Playgroud)
PERMANENT_SESSION_LIFETIME和session.permanent吗?您真正想要做的可能是使用户的登录状态过期。但是,此配置会使包含用户登录状态以及(可能)您存储在 中的其他一些数据的会话对象/cookie 过期session。
session.permanent吗?根据Flask 的文档:
Flask 的默认 cookie 实现验证加密签名不早于该值。
session.permanent是PERMANENT_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()
Run Code Online (Sandbox Code Playgroud)
如果您设置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
)
Run Code Online (Sandbox Code Playgroud)
session.permanent为每个请求设置吗?session.permanent默认情况下实际上是session['_permanent']. 它的价值将停留在session. 但是,如果您打算仅在用户登录时分配它,请通过检查用户如何绕过登录路径进行登录来保持警惕。例如,通过注册。
我选择你说的“login_user()”
@asset.route('/login', methods=['GET', 'POST'])
def login():
#After Verify the validity of username and password
session.permanent = True
Run Code Online (Sandbox Code Playgroud)
如果它设置在app.before_request,这将导致设置它们太多次。
| 归档时间: |
|
| 查看次数: |
9047 次 |
| 最近记录: |