flask之Flask-session三方组件

 1 from flask import Flask, views, render_template,  request, session, redirect
 2 import redis as redis #pip install redis
 3 from flask_session import Session#pip install Flask-session
 4 
 5 app = Flask(__name__)
 6 
 7 #使用第三方组件Flask-session就不需要设置secret_key
 8 # app.secret_key = 'wertyui234567gf!@#$%^&*('
 9 
10 app.config['SESSION_TYPE']='redis'#配置数据库类型
11 app.config['SESSION_REDIS']=redis.Redis(host='127.0.0.1',port=6379,db=6)#连接数据库,db为redis数据库的分区,一共有0-15(默认为0)16个区
12 Session(app)#自定义启用当前Flask实例session配置
13 
14 
15 class Login(views.MethodView):
16     def get(self):
17         print(request.cookies)
18         return render_template('login.html')
19 
20     def post(self):
21         username = request.form.get('username')
22         pwd = request.form.get('pwd')
23         if username == 'yang' and pwd == '123':
24             session['username'] = 'yang'#直接再使用session,生成随机字符串sessionid,
25                                         # 拼接SESSION_COOKIE_NAME+':'+seesionid得到一个字符串充当reids数据库中的key,
26                                         #通过pickle序列化key得到val,以key:val存在redis中,
27                                         #同时写入cookie返回给客户端cookie:{SESSION_COOKIE_NAME:sessionid}
28 
29             return redirect('/index')
30         else:
31             return '账号或密码有误!!!!'
32 
33 
34 def index():
35     if session.get('username'):
36 
37         return 'index'
38     else:
39         return redirect('/login')
40 
41 
42 app.add_url_rule('/login', view_func=Login.as_view(name='login'))
43 app.add_url_rule('/index',view_func=index)
44 if __name__ == '__main__':
45     app.run()

 

posted @ 2019-07-12 22:11  笑得好美  阅读(326)  评论(1编辑  收藏  举报