0
点赞
收藏
分享

微信扫一扫

Flask 学习-93.cookie 有效期设置

小猪肥 2022-10-30 阅读 188

前言

flask 框架设置cookie,如果没有指定过期时间,那么cookie 将会在浏览器关闭后过期。

set_cookie() 方法

Flask 在响应中添加一个cookie,使用内置的 Response 类提供的 set_cookie() 方法。

def set_cookie(
self,
key: str,
value: str = "",
max_age: t.Optional[t.Union[timedelta, int]] = None,
expires: t.Optional[t.Union[str, datetime, int, float]] = None,
path: t.Optional[str] = "/",
domain: t.Optional[str] = None,
secure: bool = False,
httponly: bool = False,
samesite: t.Optional[str] = None,
) -> None:
"""Sets a cookie.

相关参数说明

属性

说明

key

cookie的键

value

cookie的值

max_age

cookie被保存的时间数,单位为秒。

expires

具体的过期时间,一个datetime对象或UNIX时间戳

path

限制cookie只在给定的路径可用,默认为整个域名下路径都可用

domain

设置cookie可用的域名,默认是当前域名,子域名需要利用通配符domain=.当前域名

secure

如果设为True,只有通过HTTPS才可以用

httponly

如果设为True,禁止客户端JavaScript获取cookie

使用示例

from flask import Flask, render_template, make_response
app = Flask(__name__)


@app.route('/hello')
def hello():
resp = make_response(render_template('hello.html'))
resp.set_cookie('yoyo', '123abc')
return resp


if __name__ == '__main__':
app.run()

那么默认会在浏览器关闭后过期。

查看cookie过期时间

浏览器打开网站,查看详情

Flask 学习-93.cookie 有效期设置_flask

找到cookie名称

Flask 学习-93.cookie 有效期设置_flask_02

到期时间,显示:浏览会话结束时

Flask 学习-93.cookie 有效期设置_html_03

max_age 设置cookie过期时间

max_age 单位是秒,设置后过多少秒后失效

@app.route('/hello')
def hello():
resp = make_response(render_template('hello.html'))
resp.set_cookie('yoyo', '123abc', max_age=20)
return resp

Flask 学习-93.cookie 有效期设置_javascript_04

如果我们想设置7天后过期,可以把时间转成秒,使用max_age 参数,还有个expires 参数可以设置具体过期时间。

expires 过期时间

expires 参数是设置具体过期时间,跟前面的 max_age功能是等效的。
expires 参数为datetime类型,这个时间需要设置为格林尼治时间, 相对北京时间来说 会自动+8小时
比如设置7天后,以当前时间+7天

from datetime import datetime, timedelta

# 设置7天后
x = datetime.now() + timedelta(days=7)
print(x) # 2022-11-02 10:05:44.859928

代码示例

from flask import Flask, render_template, make_response
from datetime import datetime, timedelta
app = Flask(__name__)


@app.route('/hello')
def hello():
resp = make_response(render_template('hello.html'))
# 设置7天后过期
expires_time = datetime.now() + timedelta(days=7)
resp.set_cookie('yoyo', '123abc', expires=expires_time)
return resp

再去看浏览器上的cookie就是7天后过期了

Flask 学习-93.cookie 有效期设置_Flask_05

总结

cookie的获取和删除可以看前面这篇基础的 如果max_age和expires都设置了,那么这时候以max_age为标准。
max_age参数设置过期时间不兼容IE8一下的浏览器



举报

相关推荐

0 条评论