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