flask的cookie、session
cookie方式
1、保存cookie,通过response对象获取
response = redirect()
response = render_template()
response = Response()
response = make_response()
response = jsonify()
#通过对象调用方法
response.set_cookie(key,value,max_age)
2、获取,通过request对象获取
request.form.get()
request.args.get()
cookie也在request对象中
request.cookies.get(key)
3、删除,通过response对象删除。把浏览器的key=value删除
response = redirect()
response = render_template()
response = Response()
response = make_response()
response = jsonify()
#通过对象调用方法
reponse.delete_cookie(key)
session方式
1、保存session值
session['uid']
2、获取session的值
session.get('uid')
3、删除session的值
del session['uid']
session.clear()
@user_bp.route('/login',methods = ['GET','POST']) def login(): if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') users = User.query.filter_by(username=username).all() for user in users: flag = check_password_hash(user.password,password) if flag: # 1、cookie机制 # response = redirect(url_for('users.index')) # response.set_cookie('uid',str(user.id),max_age=3600) # return response # 2、session机制,session当成字典使用 session['uid'] = user.id return redirect(url_for('users.index')) else: return render_template('users/login.html',mag='用户名密码登陆有误') return render_template('users/login.html') @user_bp.route('/') def index(): #1、cookie的获取方式 # uid = request.cookies.get('uid',None) #2、session的获取方式 因为是字典形式 可以使用get uid = session.get('uid') if uid: user = User.query.get(uid) return render_template('users/index.html',user=user) else: return render_template('users/index.html')
@user_bp.route('/')
def logout():
response = redirect(url_for('users.index'))
#通过response对象的delete_cookie(key),key就是要删除的对象
response.delete_cookies('uid')
#删除session
del session['uid']
return respones