前言

Cookie 詳解:https://www.cnblogs.com/poloyy/p/12513247.html

這一節來瞧一瞧如何用 Flask 操作 Cookie

接下來就是 實戰慄子!!!

功能 list

提供操作 Cookie 的 3 項功能

頁面路徑 功能
/set_cookie 設定一個名稱為 poloyy、值為 https://www.cnblogs.com/poloyy 的 Cookie
/get_cooike 在服務端獲取名稱為 ‘poloyy’ 的 Cookie,並將其值返回給客戶
/del_cooike 刪除名稱為 ‘poloyy’ 的 Cookie

專案構成

程式有 3 個原始檔構成

原始檔 描述
app.py Flask 後端程式,提供操作 Cookie 的介面
templates/get_cookie.html 在服務端獲取 Cookie,顯示 Cookie 的值
templates/js_cookie.html 在客戶端通過 Javascript 顯示 Cookie 的值

模板檔案 get_cookie.html

瀏覽器訪問網站時,每次都會把 Cookie 傳送給服務端,在服務端獲取 Cookie 並返回給瀏覽器

<html>
<meta charset='UTF-8'>
<title>在服務端獲取 cookie</title> <body>
<h2>在服務端獲取 cookie: <b>{{cookie}}<b/></h2>
</body>
</html>

模板檔案 js_cookie.html

<html>
<meta charset='UTF-8'>
<title>在服務端設定 cookie</title> <body>
<h2>在服務端設定 cookie</h2>
<h2>在客戶端通過 Javascript 讀取 cookie: <b id='cookie'><b/></h2>
</body> <script>
cookie = document.getElementById('cookie');
cookie.innerHTML = document.cookie;
</script>
</html>

document.cookie 是瀏覽器端儲存的 cookie 值,在 id=cookie 中顯示 Cookie 值

Flask app.py 程式碼

引入模組

#!/usr/bin/python3
from flask import Flask, request, Response, render_template
app = Flask(__name__)

request 物件詳解:https://www.cnblogs.com/poloyy/p/14995215.html

request.cookies 就是獲取客戶端傳送的 Cookie

獲取 Cookie

@app.route("/get_cookies")
def get_cookies():
cookie = request.cookies.get('poloyy')
return render_template('get_cookie.html', cookie = cookie)

設定 Cookie

@app.route("/set_cookie")
def set_cookie():
html = render_template("js_cookie.html")
response = Response(html)
response.set_cookie("poloyy", "https://www.cnblogs.com/poloyy")
return response

刪除 Cookie

@app.route("/del_cookie")
def del_cookie():
html = render_template("js_cookie.html")
response = Response(html)
response.delete_cookie("poloyy")
return response if __name__ == '__main__':
app.run(debug=True)

瀏覽器的執行效果

設定 cookie

獲取 cookie

刪除 cookie

總結