Cookie與Session

 
 
1、Cookie

Cookie的由來:
因爲HTTP是無狀態的,瀏覽器的每次請求對於服務端來講都是全新的,而在某種特定的狀況下,咱們須要瀏覽器保持當前的某種狀態,所以就產生了Cooke。
 
先來介紹一下Cookie:
Cookie是服務器發送出來存儲到瀏覽器中的一組組鍵值對,瀏覽器再次訪問該該服務器時,會自動攜帶這些鍵值對,以便服務器從中提取有用的信息,而服務器也能夠經過這些鍵值對來判斷不一樣的用戶。
 
Cookie的使用:
1.設置Cookie
from django.shortcus import HttpResponse, render, redirect
response = HttpResponse(...)
response = render(...)
response = redirect(...)
response.set_cookie(key, value, ...)
response.set_signed_cookie(key, value, salt='..', ..)    # 設置簽名cookie
其它參數:
    max_age = None,    # 超時時間,單位是s
    expires = None,    # 超時時間,datetime格式
    path = '/',        # 生效的路徑
    domain = None,     # Cookie生效的域名
    secure = False,    # https傳輸
    httponly = False,  # 只能http傳輸,沒法被JS獲取(除抓包)
 
2.獲取Cookie的value:
request.COOKIES[key]
request.get_signed_cookie(key, default=RAISE_ERROR, salt='..', max_age=None)
 
3.刪除Cookie:
rep.delete_cookie(key)
 
4.Cookie版登錄校驗:
def check_login(func):
    @wraps(func)
    def inner(request, *args, **kwargs):
        next_url = request.get_full_path()
        if request.get_signed_cookie("login", salt="SSS", default=None) == "yes":
            # 已經登陸的用戶...
            return func(request, *args, **kwargs)
        else:
            # 沒有登陸的用戶,跳轉剛到登陸頁面
            return redirect("/login/?next={}".format(next_url))    #加這個的緣由在於讓登錄頁面獲取到它的值,而後在登錄成功以後,就自動跳轉到先前登錄的頁面
    return inner
 
def login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        passwd = request.POST.get("password")
        if username == "xxx" and passwd == "dashabi":
            next_url = request.GET.get("next")
            if next_url and next_url != "/logout/":
                response = redirect(next_url)
            else:
                response = redirect("/class_list/")
            response.set_signed_cookie("login", "yes", salt="SSS")    # 設置cookie
            return response
    return render(request, "login.html")
 
@check_login
def index(request):
    return render(request, 'index.html')
 
 
 
2、Session

Session的由來:
雖然Cookie的出現解決了HTTP請求無狀態的問題,但Cookie自己有兩個缺陷:a. Cookie自己最大支持4096個字節;b. Cookie保存在客戶端的瀏覽器上,容易被攔截或竊取,不安全。在這種狀況下Session就出現了。
 
Session的介紹:
Session和Cookie本質上是共通的,只是Session中的key(自動生成的字符串)做爲瀏覽器中Cookie的value保存在本地,而Session中的key(自動生成的字符串)和value(自定義格式存儲的用戶信息,如user)則以字典形式保存在服務器的數據庫中。
而Session依賴於Cookie,當Django用到Session時,數據庫中的key就會隨機生成一段字符串,保存到瀏覽器Cookie的value中,而這段字符串是Session用來尋找用戶信息(value)的惟一標識。
相關文章
相關標籤/搜索