Cookies
要访问 cookies ,可以使用 cookies 属性。可以使用响应 对象 的 set_cookie
方法来设置 cookies 。请求对象的 cookies 属性是一个包含了客户端传输的所有 cookies 的字典。在 Flask 中,如果使用 会话 ,那么就不要直接使用 cookies ,因为 会话比较安全一些。
储存 cookies:
from flask import make_response
@app.route('/')
def index():
# 构建响应对象
resp = make_response(render_template(...))
# 设置cookie,默认有效期是临时cookie,浏览器关闭就失效
# resp.set_cookie('username', 'the username')
# 通过max_age设置有效期,单位:秒
resp.set_cookie('username', 'the username', max_age=3600)
# 返回响应
return resp
读取 cookies:
from flask import request
@app.route('/')
def index():
username = request.cookies.get('username')
删除 cookies:
from flask import make_response
@app.route('/')
def index():
# 构建响应对象
resp = make_response(render_template(...))
# 删除cookie
resp.delete_cookie('username')
# 返回响应
return resp
make_response(* args ):
有时需要在视图中设置其他标头。因为视图不必返回响应对象,但可以返回由Flask本身转换为响应对象的值,因此向其添加标题变得棘手。可以调用此函数而不是使用return,您将获得一个可用于附加标头的响应对象。
如果视图看起来像这样,并且您想要添加响应头:
def index():
return render_template('index.html', foo=42)
你现在可以这样做:
def index():
response = make_response(render_template('index.html', foo=42))
response.headers['X-Parachutes'] = 'parachutes are cool'
return response
Session
session
的对象,允许你在不同请求 之间储存信息。这个对象相当于用密钥签名加密的 cookie ,即用户可以查看你的 cookie ,但是如果没有密钥就无法修改它。
session
使用session
之前你必须设置一个密钥。举例说明:
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
# 以下两种方式都可以
# app.secret_key = '_5#y2L"F4Q8z\n\xec]/'
app.config["SECRET_KEY"] = '_5#y2L"F4Q8z\n\xec]/'
@app.route('/')
def index():
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))
Cookie和Session的区别联系
(1)区别:
cookies:保存在浏览器上,安全性低,cookie以文本格式存储,存储量有限;
session:保存在服务器上,安全性高,session一般存储在数据库,存储量较大;
(2)联系:
cookie的目的:
由于HTTP是无状态的,在同一连接上连续执行的两个请求之间没有链接。对于试图与某些页面连贯地相互作用的用户而言,这立即存在问题。例如,我们在网页上登录某个网站时输入用户名及密码时如果保存为cookie,则每次我们访问的时候就不需要登录网站了,否则我们每次都必须输入用户信息,这是一个让人很不爽的事情。
session的目的:
如果说Cookie机制是通过检查客户身上的“通行证”来确定客户身份的话,那么Session机制就是通过检查服务器上的“客户明细表”来确认客户身份。Session相当于程序在服务器上建立的一份客户档案,客户来访的时候只需要查询客户档案表就可以了。。
cookie和session是如何联系起来的:
即服务器如何判断客户端发送过来的请求属于同一个会话?主要通过session id
联系起来。
服务器、客户端如何获取sessionID?SessionID在期间是如何传输的?
服务器第一次接收到请求时,会为这次请求开辟一块内存空间(创建了Session对象),同时生成一个Session id,并通过响应头的Set-Cookie:“JSESSIONID=XXXXXXX”命令,向客户端发送要求设置cookie的响应; 客户端收到响应后,在本机客户端设置了一个JSESSIONID=XXXXXXX的cookie信息,该cookie的过期时间为浏览器会话结束;
接下来客户端每次向同一个网站发送请求时,请求头都会带上该cookie信息(包含Session id); 然后,服务器通过读取请求头中的Cookie信息,获取名称为JSESSIONID的值,得到此次请求的Session id,以此来确认当前请求对象身份。