Django Session和Cookie分別實(shí)現(xiàn)記住用戶(hù)登錄狀態(tài)操作
簡(jiǎn)介
由于http協(xié)議的請(qǐng)求是無(wú)狀態(tài)的。故為了讓用戶(hù)在瀏覽器中再次訪問(wèn)該服務(wù)端時(shí),他的登錄狀態(tài)能夠保留(也可翻譯為該用戶(hù)訪問(wèn)這個(gè)服務(wù)端其他網(wǎng)頁(yè)時(shí)不需再重復(fù)進(jìn)行用戶(hù)認(rèn)證)。我們可以采用Cookie或Session這兩種方式來(lái)讓瀏覽器記住用戶(hù)。
Cookie與Session說(shuō)明與實(shí)現(xiàn)
Cookie
說(shuō)明
Cookie是一段小信息(數(shù)據(jù)格式一般是類(lèi)似key-value的鍵值對(duì)),由服務(wù)器生成,并發(fā)送給瀏覽器讓瀏覽器保存(保存時(shí)間由服務(wù)端定奪)。當(dāng)瀏覽器下次訪問(wèn)該服務(wù)端時(shí),會(huì)將它保存的Cookie再發(fā)給服務(wù)器,從而讓服務(wù)器根據(jù)Cookie知道是哪個(gè)瀏覽器或用戶(hù)在訪問(wèn)它。(由于瀏覽器遵從的協(xié)議,它不會(huì)把該服務(wù)器的Cookie發(fā)送給另一個(gè)不同host的服務(wù)器)。
Django中實(shí)現(xiàn)Cookie
from django.shortcuts import render, redirect # 設(shè)置cookie """ key: cookie的名字 value: cookie對(duì)應(yīng)的值 max_age: cookie過(guò)期的時(shí)間 """ response.set_cookie(key, value, max_age) # 為了安全,有時(shí)候我們會(huì)調(diào)用下面的函數(shù)來(lái)給cookie加鹽 response.set_signed_cookie(key,value,salt='加密鹽',...) # 獲取cookie request.COOKIES.get(key) request.get_signed_cookie(key, salt="加密鹽", default=None) # 刪除cookie reponse.delete_cookie(key)
下面就是具體的代碼實(shí)現(xiàn)了
views.py
# 編寫(xiě)裝飾器檢查用戶(hù)是否登錄
def check_login(func):
def inner(request, *args, **kwargs):
next_url = request.get_full_path()
# 假設(shè)設(shè)置的cookie的key為login,value為yes
if request.get_signed_cookie("login", salt="SSS", default=None) == 'yes':
# 已經(jīng)登錄的用戶(hù),則放行
return func(request, *args, **kwargs)
else:
# 沒(méi)有登錄的用戶(hù),跳轉(zhuǎn)到登錄頁(yè)面
return redirect(f"/login?next={next_url}")
return inner
# 編寫(xiě)用戶(hù)登錄頁(yè)面的控制函數(shù)
@csrf_exempt
def login(request):
if request.method == "POST":
username = request.POST.get("username")
passwd = request.POST.get("password")
next_url = request.POST.get("next_url")
# 對(duì)用戶(hù)進(jìn)行驗(yàn)證,假設(shè)用戶(hù)名為:aaa, 密碼為123
if username === 'aaa' and passwd == '123':
# 執(zhí)行其他邏輯操作,例如保存用戶(hù)信息到數(shù)據(jù)庫(kù)等
# print(f'next_url={next_url}')
# 登錄成功后跳轉(zhuǎn),否則直接回到主頁(yè)面
if next_url and next_url != "/logout/":
response = redirect(next_url)
else:
response = redirect("/index/")
# 若登錄成功,則設(shè)置cookie,加鹽值可自己定義取,這里定義12小時(shí)后cookie過(guò)期
response.set_signed_cookie("login", 'yes', salt="SSS", max_age=60*60*12)
return response
else:
# 登錄失敗,則返回失敗提示到登錄頁(yè)面
error_msg = '登錄驗(yàn)證失敗,請(qǐng)重新嘗試'
return render(request, "app/login.html", {
'login_error_msg': error_msg,
'next_url': next_url,
})
# 用戶(hù)剛進(jìn)入登錄頁(yè)面時(shí),獲取到跳轉(zhuǎn)鏈接,并保存
next_url = request.GET.get("next", '')
return render(request, "app/login.html", {
'next_url': next_url
})
# 登出頁(yè)面
def logout(request):
rep = redirect("/login/")
# 刪除用戶(hù)瀏覽器上之前設(shè)置的cookie
rep.delete_cookie('login')
return rep
# 給主頁(yè)添加登錄權(quán)限認(rèn)證
@check_login
def index(request):
return render(request, "app/index.html")
由上面看出,其實(shí)就是在第一次用戶(hù)登錄成功時(shí),設(shè)置cookie,用戶(hù)訪問(wèn)其他頁(yè)面時(shí)進(jìn)行cookie驗(yàn)證,用戶(hù)登出時(shí)刪除cookie。另外附上前端的login.html部分代碼
<form action="{% url 'login' %}" method="post">
<h1>請(qǐng)使xx賬戶(hù)登錄</h1>
<div>
<input id="user" type="text" class="form-control" name="username" placeholder="賬戶(hù)" required="" />
</div>
<div>
<input id="pwd" type="password" class="form-control" name="password" placeholder="密碼" required="" />
</div>
<div style="display: none;">
<input id="next" type="text" name="next_url" value="{{ next_url }}" />
</div>
{% if login_error_msg %}
<div id="error-msg">
<span style="color: rgba(255,53,49,0.8); font-family: cursive;">{{ login_error_msg }}</span>
</div>
{% endif %}
<div>
<button type="submit" class="btn btn-default" style="float: initial; margin-left: 0px">登錄</button>
</div>
</form>
Session
Session說(shuō)明
Session則是為了保證用戶(hù)信息的安全,將這些信息保存到服務(wù)端進(jìn)行驗(yàn)證的一種方式。但它卻依賴(lài)于cookie。具體的過(guò)程是:服務(wù)端給每個(gè)客戶(hù)端(即瀏覽器)設(shè)置一個(gè)cookie(從上面的cookie我們知道,cookie是一種”key, value“形式的數(shù)據(jù),這個(gè)cookie的value是服務(wù)端隨機(jī)生成的一段但唯一的值)。
當(dāng)客戶(hù)端下次訪問(wèn)該服務(wù)端時(shí),它將cookie傳遞給服務(wù)端,服務(wù)端得到cookie,根據(jù)該cookie的value去服務(wù)端的Session數(shù)據(jù)庫(kù)中找到該value對(duì)應(yīng)的用戶(hù)信息。(Django中在應(yīng)用的setting.py中配置Session數(shù)據(jù)庫(kù))。
根據(jù)以上描述,我們知道Session把用戶(hù)的敏感信息都保存到了服務(wù)端數(shù)據(jù)庫(kù)中,這樣具有較高的安全性。
Django中Session的實(shí)現(xiàn)
# 設(shè)置session數(shù)據(jù), key是字符串,value可以是任何值 request.session[key] = value # 獲取 session request.session.get[key] # 刪除 session中的某個(gè)數(shù)據(jù) del request.session[key] # 清空session中的所有數(shù)據(jù) request.session.delete()
下面就是具體的代碼實(shí)現(xiàn)了:
首先就是設(shè)置保存session的數(shù)據(jù)庫(kù)了。這個(gè)在setting.py中配置:(注意我這里數(shù)據(jù)庫(kù)用的mongodb,并使用了django_mongoengine庫(kù);關(guān)于這個(gè)配置請(qǐng)根據(jù)自己使用的數(shù)據(jù)庫(kù)進(jìn)行選擇,具體配置可參考官方教程)
SESSION_ENGINE = 'django_mongoengine.sessions'
SESSION_SERIALIZER = 'django_mongoengine.sessions.BSONSerializer'
views.py
# 編寫(xiě)裝飾器檢查用戶(hù)是否登錄
def check_login(func):
def inner(request, *args, **kwargs):
next_url = request.get_full_path()
# 獲取session判斷用戶(hù)是否已登錄
if request.session.get('is_login'):
# 已經(jīng)登錄的用戶(hù)...
return func(request, *args, **kwargs)
else:
# 沒(méi)有登錄的用戶(hù),跳轉(zhuǎn)剛到登錄頁(yè)面
return redirect(f"/login?next={next_url}")
return inner
@csrf_exempt
def login(request):
if request.method == "POST":
username = request.POST.get("username")
passwd = request.POST.get("password")
next_url = request.POST.get("next_url")
# 若是有記住密碼功能
# remember_sign = request.POST.get("check_remember")
# print(remember_sign)
# 對(duì)用戶(hù)進(jìn)行驗(yàn)證
if username == 'aaa' and passwd == '123':
# 進(jìn)行邏輯處理,比如保存用戶(hù)與密碼到數(shù)據(jù)庫(kù)
# 若要使用記住密碼功能,可保存用戶(hù)名、密碼到session
# request.session['user_info'] = {
# 'username': username,
# 'password': passwd
# }
request.session['is_login'] = True
# 判斷是否勾選了記住密碼的復(fù)選框
# if remember_sign == 'on':
# request.session['is_remember'] = True
# else:
# request.session['is_remember'] = False
# print(f'next_url={next_url}')
if next_url and next_url != "/logout/":
response = redirect(next_url)
else:
response = redirect("/index/")
return response
else:
error_msg = '登錄驗(yàn)證失敗,請(qǐng)重新嘗試'
return render(request, "app/login.html", {
'login_error_msg': error_msg,
'next_url': next_url,
})
next_url = request.GET.get("next", '')
# 檢查是否勾選了記住密碼功能
# password, check_value = '', ''
# user_session = request.session.get('user_info', {})
# username = user_session.get('username', '')
# print(user_session)
#if request.session.get('is_remember'):
# password = user_session.get('password', '')
# check_value = 'checked'
# print(username, password)
return render(request, "app/login.html", {
'next_url': next_url,
# 'user': username,
# 'password': password,
# 'check_value': check_value
})
def logout(request):
rep = redirect("/login/")
# request.session.delete()
# 登出,則刪除掉session中的某條數(shù)據(jù)
if 'is_login' in request.session:
del request.session['is_login']
return rep
@check_login
def index(request):
return render(request, "autotest/index.html")
另附login.html部分代碼:
<form action="{% url 'login' %}" method="post">
<h1>請(qǐng)使xxx賬戶(hù)登錄</h1>
<div>
<input id="user" type="text" class="form-control" name="username" placeholder="用戶(hù)" required="" value="{{ user }}" />
</div>
<div>
<input id="pwd" type="password" class="form-control" name="password" placeholder="密碼" required="" value="{{ password }}" />
</div>
<div style="display: none;">
<input id="next" type="text" name="next_url" value="{{ next_url }}" />
</div>
{% if login_error_msg %}
<div id="error-msg">
<span style="color: rgba(255,53,49,0.8); font-family: cursive;">{{ login_error_msg }}</span>
</div>
{% endif %}
// 若設(shè)置了記住密碼功能
// <div style="float: left">
// <input id="rmb-me" type="checkbox" name="check_remember" {{ check_value }}/>記住密碼
// </div>
<div>
<button type="submit" class="btn btn-default" style="float: initial; margin-right: 60px">登錄</button>
</div>
</form>
總的來(lái)看,session也是利用了cookie,通過(guò)cookie生成的value的唯一性,從而在后端數(shù)據(jù)庫(kù)session表中找到這value對(duì)應(yīng)的數(shù)據(jù)。session的用法可以保存更多的用戶(hù)信息,并使這些信息不易被暴露。
總結(jié)
session和cookie都能實(shí)現(xiàn)記住用戶(hù)登錄狀態(tài)的功能,如果為了安全起見(jiàn),還是使用session更合適
以上這篇Django Session和Cookie分別實(shí)現(xiàn)記住用戶(hù)登錄狀態(tài)操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python數(shù)據(jù)類(lèi)型相互轉(zhuǎn)換
當(dāng)涉及數(shù)據(jù)類(lèi)型轉(zhuǎn)換時(shí),Python提供了多種內(nèi)置函數(shù)來(lái)執(zhí)行不同類(lèi)型之間的轉(zhuǎn)換,本文主要介紹了Python數(shù)據(jù)類(lèi)型相互轉(zhuǎn)換,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09
python+selenium實(shí)現(xiàn)QQ郵箱自動(dòng)發(fā)送功能
這篇文章主要為大家詳細(xì)介紹了python+selenium實(shí)現(xiàn)QQ郵箱自動(dòng)發(fā)送功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01
深入理解Python虛擬機(jī)中字典(dict)的實(shí)現(xiàn)原理及源碼剖析
這篇文章主要介紹了在?cpython?當(dāng)中字典的實(shí)現(xiàn)原理,在本篇文章當(dāng)中主要介紹在早期?python3?當(dāng)中的版本字典的實(shí)現(xiàn),現(xiàn)在的字典做了部分優(yōu)化,希望對(duì)大家有所幫助2023-03-03

