[Flask教學] 5分鐘快速設定 Flask 取得 Cookie

Flask教學_cookie_Max行銷誌

一. Cookie 解決了什麼問題?

An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user’s web browser. The browser may store it and send it back with the next request to the same server. Typically, it’s used to tell if two requests came from the same browser — keeping a user logged-in, for example. It remembers stateful information for the stateless HTTP protocol.

HTTP cookies – HTTP | MDN

因為 HTTP stateless 無狀態的設計,Cookie 提供了更容易實現保存 Session 的方式,來讓 HTTP request 保有狀態的功能,達到區分出不同的 HTTP request 是來自同一個瀏覽器。

Cookie 保存 Session 通常用於兩種情境:

  1. Session management
    用於登入頁、購物車頁面,藉由 Cookie 保留使用者的狀態,來提升使用者流程體驗。
  2. Tracking
    像是廣告的數據追蹤,就很常需要使用到 Cookie 的功能。

二. 如何實現 Cookie 功能?

When receiving an HTTP request, a server can send a Set-Cookie header with the response. The cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a Cookie HTTP header. An expiration date or duration can be specified, after which the cookie is no longer sent. Additionally, restrictions to a specific domain and path can be set, limiting where the cookie is sent.

HTTP cookies – HTTP | MDN

當 Server 收到 HTTP request 請求時,會將 Cookie 放在 HTTP response 的 header 中作為返回

而 Browser 收到返回的 HTTP response 後,會將 Cookie 保存在用戶的本機端。未來當發送相同網域的 HTTP request 時,此 Cookie 會被放在 header 中一同被發送。

三. Flask 操作 Cookie

首先我們來看一下 Flask 如何設定 Cookie,今天會分成三個部分來教學:

  1. 設定 Cookie
  2. 取得 Cookie
  3. 刪除 Cookie

1. Flask 設定 Cookie

參考:Flask set_cookie 官方文件

  1. key: 是 cookie 的名稱 (此為必填欄位)
  2. value:是 cookie 的值
  3. expires:指定 Cookie 的有效日期, 當過了有效日期後, 那個 Cookie 就不會再儲存在瀏覽器;如果不指定這個參數, 該 Cookie 的有效日期就是使用者退出瀏覽器時 (End of Browser Session)。
  4. max_age:功能和 expires 很像,但此參數並非所有瀏覽器均支持,所以建議使用 expires 參數。
  5. path:指定可以存取該 Cookie 的路徑, 如果瀏覽器要求的 URL 乎合 cookie 的網域和路徑名稱 (domain 和 path), 就會傳送該 cookie 到伺服器。 如果不指定這個參數, path 就指定為設定該 cookie 的網頁所在的路徑
  6. domain:指定可以存取該 cookie 的網域。 如果不指定這個參數, domain 就指定為設定該 cookie 的網頁所在的網域
  7. secure:如果設定為 True,表示此 cookie 僅在 Https 時才被傳送
  8. httponly:如設定為 True,表示 JavaScript 的 Document.cookie API 無法取得 HttpOnly cookies
  9. samesite:可以設定成 Strict、Lax 和 None,由嚴格至寬鬆不同程度地限制 cookies 的傳輸

此次設定參數為 key、value、expires 時間,利用 set_cookie 的方法設定,可以在瀏覽器看到的畫面如下:

flask_set_cookie
Flask 設定 cookie

2.Flask 取得 Cookie

利用 request.cookies.get 的方法取得要的 Cookie name 即可拿到剛剛設定的 cookie

flask_set_cookie
Flask 取得 cookie

3.Flask 刪除 Cookie

刪除 Cookie 的方法其實很簡單,就把 expires 日期設定為 0,就會自動刪除囉

flask_del_cookie
Flask 刪除 cookie

最後就是運行指令:python main.py 快去試試看吧!

完整的代碼如下:

最後~

▍回顧本篇的 Flask 設定 Cookie 教學內容:

  • Cookie 解決了什麼問題?
  • 如何實現 Cookie 功能?
  • Flask 操作 Cookie
    1. 如何設定 Cookie
    2. 取得
    3. 刪除

關於 Flask 教學的延伸閱讀:

▍關於 Flask 教學系列目錄:

▍其他 Flask 相關教學:

[Flask教學] 5分鐘快速設定 Flask 取得 Cookie 結束囉,感謝收看!如有任何問題歡迎留言唷

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *