项目名称为 third_template
目录
1??cookie
1.1??设置
1.2??读取
1.3??删除
2??session
2.1??设置
2.2??获取
1??cookie
cookie是储存在用户本地上的数据,一般用来辨明用户身份
1.1??设置
我们可以通过make_response中的set_cookie设置cookie

我们访问一下

发现可以看到cookie的数据,我们也可以在这里查看cookie

在这里可以看到我们cookie的信息

在信息下方会有cookie的有效期,默认是浏览会话结束时失效,我们将这种cookie称为临时cookie

我们可以通过max_age参数,来设置cookie的有效期,我们现在设置为3600秒(一小时)

访问之后我们看一下cookie

我们观察响应头可以发现设置cookie实则是在响应头中加入了Set-Cookie这个属性

1.2??读取
一般来讲我们都是通过一个路由把cookie给出去,然后再到另一个路由中读cookie,我们现在写一个视图使用request.cookies.get()读cookie

我们现在访问一下

那我们现在在浏览器中给浏览器删了

删除之后我们再访问一下

1.3??删除
我们可以让有这个cookie时怎么做,没有这个cookie时就做另一件事,所以在服务端删除cookie也是很有必要的
我们使用delete_cookie删除cookie

运行后首先我们先访问 127.0.0.1/set_cookie 设置一个cookie

之后我们再访问 127.0.0.1/delete_cookie 删除一个cookie

我们发现 到期时间 给了一个奇异的值,我们现在访问 127.0.0.1/load_cookie 看一下

发现那个奇异的值其实代表的就是cookie没了
- 设置cookie是在响应头加入了Set-cookie这个属性,删除cookie实则就是把Set-cookie这个属性变为空值且有效期会给到要给很早的日期,上面显示的50000多年是解码问题
2??session
首先我们说一下session与cookie的区别
- 存储位置 理论上session存储在服务器的缓存中,cookie存储在客户端,但是flask在默认情况下使用的是浏览器session,也就是说session与cookie是一样的
- 作用对象 cookie是针对网站的,session是针对用户的,如果我搞了一个登陆界面,我像让用户在第二次进入登陆界面时不要再登陆一边,那么我就要将用户名与密码数据放在session中而不是cookie中
他们的相同点就是根据不同的信息返回不同的页面,所以在下面我们看到处理方式很相似
在使用session前,我们首先需要设置SECRET_KEY

2.1??设置

我们访问一下

我们在这里可以看到session,这里的密文是配合我们之前设置的SECRET_KEY生成的
也可以在这里看

2.2??获取

我们访问一下

|