1 '''
2 session使用:
3 session创建:
4 (1)导入session from flask import session
5 (2)设置secret_key密钥 app.secret_key='sggdkhfjh3jgj4g4'
6 (3)使用session: session[key]=value
7 ①创建session字典;
8 ②通过secret_key + 时间戳 + 签名进行加密生成随机字符串;
9 ③将随机字符串写入到cookie中并返回给浏览器
10
11 session登录验证:
12 (1)客户端请求携带cookie中的存储的seesiond的加密字符串;
13 (2)flask服务端收到session随机字符串通过secret_key进行解密得到session字典
14
15
16 session验证方式:
17 (1)直接在每个view_func函数进行判断session字典的值
18 (2)使用装饰器对vuew_func视图函数进行装饰,解决报错方式如下(二选一即可):
19 ①注意在路由中加上参数endpoint='唯一字符串'(指定在view_funcs视图函数字典中的key),否则报错inner已经存在
20 ②在装饰器函数的inner函数上加上装饰器@funuctools.wraps(impoert functools)
21 (3)还可以通过在@app.before_request装饰的函数中进行校验(类似于django中间件功能,后续讲解)
22
23
24
25 '''
26 from flask import Flask, render_template, request, session, redirect
27
28 app=Flask(__name__)
29 app.secret_key='sdertyuhgfd23456q' #seesion秘钥自定义
30
31 #自定义设置cookie中存储的键
32 # app.config['SESSION_COOKIE_NAME']='NOT session'
33 #自定义设置cookie有效期,本设置单位是秒
34 # app.config['PERMANENT_SESSION_LIFETIME']=1000
35
36
37
38 @app.route('/login',methods=['GET','post'])#请求方式配置大小写均可
39 def login():
40 print(request.method)
41 if request.method=='GET':
42 return render_template('login.html')
43 elif request.method=='POST':
44 username=request.form.get('username')
45 pwd=request.form.get('pwd')
46 if username=='yang' and pwd=='123':
47 session['username']=username
48 return redirect('/')
49
50 else:
51 return 'login failed!'
52
53
54
55
56 #(1)进入视图函数中进行session验证
57 @app.route('/')
58 def index():
59 if session.get('username'):
60 return render_template('index.html')
61 else:
62 return redirect('/login')
63
64
65 #(2)装饰器进行session判断之functools.wraps装饰器
66 def auth(func):
67 @functools.wraps(func)
68 def inner(*args, **kwargs):
69 if session.get('username'):
70 return func()
71 else:
72 return redirect('/login')
73 return inner
74
75
76 @app.route('/index1')
77 @auth
78 def index1():
79 return render_template('index.html')
80
81
82 @app.route('/index2')
83 @auth
84 def index2():
85 return render_template('index.html')
86
87
88
89 #(3)装饰器进行session判断之endpoint参数设置
90 def auth2(func):
91 def inner(*args, **kwargs):
92 if session.get('username'):
93 return func()
94 else:
95 return redirect('/login')
96 return inner
97
98 @app.route('/index3',endpoint='index3')
99 @auth2
100 def index3():
101 return render_template('index.html')
102
103
104 @app.route('/index4',endpoint='index4')
105 @auth2
106 def index4():
107 return render_template('index.html')
108
109
110
111 if __name__ == '__main__':
112 app.run(host='0.0.0.0',port=9000,debug=True
113