Cookie以文本文件的形式存儲(chǔ)在客戶(hù)端的計(jì)算機(jī)上。其目的是記住和跟蹤與客戶(hù)使用相關(guān)的數(shù)據(jù),以獲得更好的訪(fǎng)問(wèn)者體驗(yàn)和網(wǎng)站統(tǒng)計(jì)信息。
Request對(duì)象包含Cookie的屬性。它是所有cookie變量及其對(duì)應(yīng)值的字典對(duì)象,客戶(hù)端已傳輸。除此之外,cookie還存儲(chǔ)其網(wǎng)站的到期時(shí)間,路徑和域名。
在Flask中,對(duì)響應(yīng)對(duì)象設(shè)置cookie。使用make_response()函數(shù)從視圖函數(shù)的返回值獲取響應(yīng)對(duì)象。之后,使用響應(yīng)對(duì)象的set_cookie()函數(shù)來(lái)存儲(chǔ)cookie。
讀回cookie很容易。request.cookies屬性的get()方法用于讀取cookie。
在以下Flask應(yīng)用程序中,當(dāng)您訪(fǎng)問(wèn)'/' URL時(shí),會(huì)打開(kāi)一個(gè)簡(jiǎn)單的表單。
@app.route('/')
def index():
return render_template('index.html')
此HTML頁(yè)面包含一個(gè)文本輸入。
<html>
<body>
<form action = "/setcookie" method = "POST">
<p><h3>Enter userID</h3></p>
<p><input type = 'text' name = 'nm'/></p>
<p><input type = 'submit' value = 'Login'/></p>
</form>
</body>
</html>
表單發(fā)布到'/ setcookie' URL。相關(guān)聯(lián)的視圖函數(shù)設(shè)置Cookie名稱(chēng)userID并呈現(xiàn)另一個(gè)頁(yè)面。
@app.route('/setcookie', methods = ['POST', 'GET'])
def setcookie():
if request.method == 'POST':
user = request.form['nm']
resp = make_response(render_template('readcookie.html'))
resp.set_cookie('userID', user)
return resp
'readcookie.html'包含指向另一個(gè)視圖函數(shù)getcookie()的超鏈接,它讀回并在瀏覽器中顯示Cookie值。
@app.route('/getcookie')
def getcookie():
name = request.cookies.get('userID')
return '<h1>welcome '+name+'</h1>'
運(yùn)行應(yīng)用程序,并訪(fǎng)問(wèn)http://localhost:5000/
設(shè)置cookie的結(jié)果顯示為這樣:
讀回cookie的輸出如下所示:
更多建議: