Flask Sessions(會話)
與 Cookie 不同,Session(會話)數據存儲在服務器上。會話是客戶端登錄到服務器並註銷服務器的時間間隔。需要在該會話中保存的數據會存儲在服務器上的臨時目錄中。
爲每個客戶端的會話分配會話 ID。會話數據存儲在 cookie 的頂部,服務器以加密方式對其進行簽名。對於此加密,Flask 應用程序需要一個定義的 SECRET_KEY。
Session 對象也是一個字典對象,包含會話變量和關聯值的鍵值對。
例如,要設置一個 ‘username’ 會話變量,請使用以下語句:
Session[‘username’] = ’admin’
要釋放會話變量,請使用 pop() 方法。
session.pop('username', None)
以下代碼是 Flask 中的會話工作的簡單演示。URL ‘/’ 只是提示用戶登錄,因爲未設置會話變量 ‘username’。
@app.route('/')
def index():
if 'username' in session:
username = session['username']
return 'Logged in as ' + username + '<br>' + \
"<b><a href = '/logout'>click here to log out</a></b>"
else:
return "You are not logged in <br><a href = '/login'></b>" + \
"click here to log in</b></a>"
當用戶瀏覽到 “/login” login() 視圖函數時,因爲它是通過 GET 方法調用的,所以將打開一個登錄表單。
表單發送回 ‘/login’,現在會話變量已設置。應用程序重定向到 ‘/’。此時會話變量 ‘username’ 被找到。
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
else:
return '''
<form action = "" method = "post">
<p><input type = text name = username /></p>
<p><input type = submit value = Login /></p>
</form>'''
應用程序還包含一個 logout() 視圖函數,它會彈出 ‘username’ 會話變量。因此,’/’ URL 再次顯示開始頁面。
@app.route('/logout')
def logout():
# remove the username from the session if it is there
session.pop('username', None)
return redirect(url_for('index'))
運行應用程序並訪問主頁。(確保設置應用程序的 secret_key )
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
app.secret_key = 'any random string’
輸出將顯示如下。
點擊“點擊此處登錄”鏈接,輸入 name 並點擊登陸。
程序將跳轉回首頁,並顯示登陸信息:
點擊退出,程序將清除登陸狀態