flask session工作机制:
把敏感数据经过加密后放入到‘session’中,然后在把'session'存放到cookie中,下次请求的时候,再从浏览器发送过来的cookie中读取session,在从session中读取敏感数据,并进行解密,获取最终的用户数据,这种session机制可以节省服务器开销,因为所有的信息都存到了客户端
操作session
from flask import Flask,session
import os app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom() #设置secret_key 用来作为加盐加密使用,每次服务重启后都会变化,之前的session就不能用这个来解密了 @app.route('/')
def hello_world():
session['username'] = 'bb' #添加session
return 'Hello World!' @app.route('/get/')
def get(): #获取session
return session.get('username') @app.route('/delete/')
def delete(): #删除session
session.pop('username') #删除session
#session.clear() #清空session里的所有数据return "sucess" if __name__ == '__main__':
app.run(host='192.168.132.130',debug=True)
使用案例:
#!/usr/bin/env python
#-*-coding:utf-8-*- from . import homebapp
from flask import render_template,redirect,url_for,request,flash,session,send_from_directory
from models import User,UserLog
from .forms import RegistUser,LoginForm,UserForm
from werkzeug.security import generate_password_hash
from movie_project import db,app
import uuid,os
from functools import wraps
from werkzeug.utils import secure_filename
#登录的装饰器,利用session控制
def login_required(func):
@wraps(func)
def decorated_function(*args, **kwargs):
if session.get('user'): #验证session
return func(*args, **kwargs)
else:
return redirect(url_for('home.login',next=request.url))
return decorated_function @homebapp.route("/login/",methods=['GET','POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
data = form.data
user = User.query.filter_by(name=data['account']).first()
if user is None:
flash("账号不存在",'err')
return redirect(url_for('home.login'))
else:
if not user.check_pwd(data['pwd']):
print (data['pwd'])
flash("密码不正确",'err')
return redirect(url_for('home.login'))
flash("登录成功",'ok')
session['user_id'] = user.id #登录成功,添加session
session['user'] = user.name
userlog = UserLog(
user_id = user.id,
ip=request.remote_addr
)
db.session.add(userlog)
db.session.commit()
return redirect(url_for('home.user')) return render_template('home/login.html',form=form) #登出操作清除session
@homebapp.route("/logout/")
def logout():
session.pop('user',None)
session.pop('user_id',None)
return redirect(url_for('home.login')) @homebapp.route('/user/',methods=['GET','POST'])
@login_required
def user():
form = UserForm()
user = User.query.get(int(session['user_id']))
form.face.validators = []
if request.method == 'GET':
form.name.data = user.name
form.email.data = user.email
form.phone.data = user.phone
form.des.data = user.info
if form.validate_on_submit():
data = form.data
return render_template('home/user.html',form = form,user=user)