Cookie以文本文件的形式存儲(chǔ)在客戶端計(jì)算機(jī)上。 其目的是記住和跟蹤與客戶使用有關(guān)的數(shù)據(jù),以獲得更好的訪問(wèn)體驗(yàn)和網(wǎng)站統(tǒng)計(jì)。
Request對(duì)象包含一個(gè)cookie的屬性。 它是所有cookie變量及其對(duì)應(yīng)值的字典對(duì)象,客戶端已發(fā)送。 除此之外,cookie還會(huì)存儲(chǔ)其到期時(shí)間,路徑和站點(diǎn)的域名。
在Flask中,cookies設(shè)置在響應(yīng)對(duì)象上。 使用make_response()函數(shù)從視圖函數(shù)的返回值中獲取響應(yīng)對(duì)象。 之后,使用響應(yīng)對(duì)象的set_cookie()函數(shù)來(lái)存儲(chǔ)cookie。
重讀cookie很容易。 可以使用request.cookies屬性的get()方法來(lái)讀取cookie。
在下面的Flask應(yīng)用程序中,當(dāng)訪問(wèn)URL => / 時(shí),會(huì)打開(kāi)一個(gè)簡(jiǎn)單的表單。
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.soo66.com # Date : 2020-08-08 @app.route('/') def index(): return render_template('index.html')
這個(gè)HTML頁(yè)面包含一個(gè)文本輸入,完整代碼如下所示 -
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.soo66.com # Date : 2020-08-08 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Flask Cookies示例</title> </head> <body> <form action = "/setcookie" method = "POST"> <p><h3>Enter userID</h3></p> <p><input type = 'text' name = 'name'/></p> <p><input type = 'submit' value = '登錄'/></p> </form> </body> </html>
表單提交到URL => /setcookie。 關(guān)聯(lián)的視圖函數(shù)設(shè)置一個(gè)Cookie名稱為:userID,并的另一個(gè)頁(yè)面中呈現(xiàn)。
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.soo66.com # Date : 2020-08-08 @app.route('/setcookie', methods = ['POST', 'GET']) def setcookie(): if request.method == 'POST': user = request.form['name'] resp = make_response(render_template('readcookie.html')) resp.set_cookie('userID', user) return resp
readcookie.html 包含超鏈接到另一個(gè)函數(shù)getcookie()的視圖,該函數(shù)讀回并在瀏覽器中顯示cookie值。
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.soo66.com # Date : 2020-08-08 @app.route('/getcookie') def getcookie(): name = request.cookies.get('userID') return '<h1>welcome '+name+'</h1>'
完整的應(yīng)用程序代碼如下 -
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.soo66.com # Date : 2020-08-08 from flask import Flask from flask import render_template from flask import request from flask import make_response app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/setcookie', methods = ['POST', 'GET']) def setcookie(): if request.method == 'POST': user = request.form['name'] resp = make_response(render_template('readcookie.html')) resp.set_cookie('userID', user) return resp @app.route('/getcookie') def getcookie(): name = request.cookies.get('userID') print (name) return '<h1>welcome, '+name+'</h1>' if __name__ == '__main__': app.run(debug = True)
運(yùn)行該應(yīng)用程序并訪問(wèn)URL => http://localhost:5000/設(shè)置cookie的結(jié)果如下所示 -
重讀cookie的輸出如下所示 -