溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Django設(shè)置Cookie的過期時(shí)間expires, max_age的格式

發(fā)布時(shí)間:2020-06-20 00:47:20 來源:網(wǎng)絡(luò) 閱讀:2383 作者:龍翔九天dl 欄目:編程語言

cookie中 max_age和expires的關(guān)系:

1. 若沒有填寫 max_age, expires ,默認(rèn)都為None
    此時(shí)該cooike為臨時(shí)的,只存在瀏覽器內(nèi)存中, 關(guān)閉瀏覽器則自動刪除
2. 只有max_age,  則按秒計(jì)算過期時(shí)間, 瀏覽器會存在本地緩存路徑, 并自動刪除過期cookie
3. 只有expires,  則按照時(shí)間字符串計(jì)算過期時(shí)間, 瀏覽器會存在本地緩存路徑, 自動刪除過期cookie
3. 若 max_age和 expires 同時(shí)存在,  則默認(rèn)使用 max_age
4. 如果設(shè)置的cookie時(shí)間小于計(jì)算機(jī)時(shí)間, 瀏覽器則不提取cookie

max_age 格式:

max_age = 60*60*24   #按秒計(jì)算

expires 格式:

expires格式可以為:
    1.時(shí)間格式的字符串 : " Wdy, DD-Mth-YY HH:MM:SS GMT " 
    2.秒數(shù)
    3.datetime.datetime 對象
例:
expires = 'Thu, 28-May-2020 08:53:06 GMT'       # 24小時(shí) 格林威治時(shí)間
expires = datetime.datetime(2020, 5, 28, 23, 44, 55))
expires = 60 * 60 * 24

通過Chrome 查看設(shè)置完畢的效果:

Django設(shè)置Cookie的過期時(shí)間expires, max_age的格式
Django設(shè)置Cookie的過期時(shí)間expires, max_age的格式


為方便使用,可以自定義方法, 智能設(shè)置expires的過期時(shí)間

from django.conf import settings
import datetime

def set_cookie(response, key, value, expire=None):
    if expire is None:
        max_age = 365*24*60*60  #默認(rèn)max_age為一年, 如果存在expires,則覆蓋max_age
    else:
        max_age = expire
    expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT")
    response.set_cookie(key, value, max_age=max_age, expires=expires, 
    domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None)

本文參考并總結(jié): https://www.djangosnippets.org/snippets/40/

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI