最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Django Session和Cookie分別實(shí)現(xiàn)記住用戶登錄狀態(tài)操作

 更新時(shí)間:2020年07月02日 15:47:24   作者:xiaobai_ol  
這篇文章主要介紹了Django Session和Cookie分別實(shí)現(xiàn)記住用戶登錄狀態(tài)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

簡介

由于http協(xié)議的請求是無狀態(tài)的。故為了讓用戶在瀏覽器中再次訪問該服務(wù)端時(shí),他的登錄狀態(tài)能夠保留(也可翻譯為該用戶訪問這個(gè)服務(wù)端其他網(wǎng)頁時(shí)不需再重復(fù)進(jìn)行用戶認(rèn)證)。我們可以采用Cookie或Session這兩種方式來讓瀏覽器記住用戶。

Cookie與Session說明與實(shí)現(xiàn)

Cookie

說明

Cookie是一段小信息(數(shù)據(jù)格式一般是類似key-value的鍵值對(duì)),由服務(wù)器生成,并發(fā)送給瀏覽器讓瀏覽器保存(保存時(shí)間由服務(wù)端定奪)。當(dāng)瀏覽器下次訪問該服務(wù)端時(shí),會(huì)將它保存的Cookie再發(fā)給服務(wù)器,從而讓服務(wù)器根據(jù)Cookie知道是哪個(gè)瀏覽器或用戶在訪問它。(由于瀏覽器遵從的協(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過期的時(shí)間
"""
response.set_cookie(key, value, max_age)
# 為了安全,有時(shí)候我們會(huì)調(diào)用下面的函數(shù)來給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

# 編寫裝飾器檢查用戶是否登錄
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)登錄的用戶,則放行
  return func(request, *args, **kwargs)
 else:
  # 沒有登錄的用戶,跳轉(zhuǎn)到登錄頁面
  return redirect(f"/login?next={next_url}")
 return inner

# 編寫用戶登錄頁面的控制函數(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ì)用戶進(jìn)行驗(yàn)證,假設(shè)用戶名為:aaa, 密碼為123
 if username === 'aaa' and passwd == '123':
  # 執(zhí)行其他邏輯操作,例如保存用戶信息到數(shù)據(jù)庫等
  # print(f'next_url={next_url}')
  # 登錄成功后跳轉(zhuǎn),否則直接回到主頁面
  if next_url and next_url != "/logout/":
  response = redirect(next_url)
  else:
  response = redirect("/index/")
  # 若登錄成功,則設(shè)置cookie,加鹽值可自己定義取,這里定義12小時(shí)后cookie過期
  response.set_signed_cookie("login", 'yes', salt="SSS", max_age=60*60*12)
  return response
 else:
  # 登錄失敗,則返回失敗提示到登錄頁面
  error_msg = '登錄驗(yàn)證失敗,請重新嘗試'
  return render(request, "app/login.html", {
  'login_error_msg': error_msg,
  'next_url': next_url,
  })
 # 用戶剛進(jìn)入登錄頁面時(shí),獲取到跳轉(zhuǎn)鏈接,并保存
 next_url = request.GET.get("next", '')
 return render(request, "app/login.html", {
 'next_url': next_url
 })

# 登出頁面
def logout(request):
 rep = redirect("/login/")
 # 刪除用戶瀏覽器上之前設(shè)置的cookie
 rep.delete_cookie('login')
 return rep

# 給主頁添加登錄權(quán)限認(rèn)證
@check_login
def index(request):
 return render(request, "app/index.html")

由上面看出,其實(shí)就是在第一次用戶登錄成功時(shí),設(shè)置cookie,用戶訪問其他頁面時(shí)進(jìn)行cookie驗(yàn)證,用戶登出時(shí)刪除cookie。另外附上前端的login.html部分代碼

<form action="{% url 'login' %}" method="post">
  <h1>請使xx賬戶登錄</h1>
  <div>
  <input id="user" type="text" class="form-control" name="username" placeholder="賬戶" 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說明

Session則是為了保證用戶信息的安全,將這些信息保存到服務(wù)端進(jìn)行驗(yàn)證的一種方式。但它卻依賴于cookie。具體的過程是:服務(wù)端給每個(gè)客戶端(即瀏覽器)設(shè)置一個(gè)cookie(從上面的cookie我們知道,cookie是一種”key, value“形式的數(shù)據(jù),這個(gè)cookie的value是服務(wù)端隨機(jī)生成的一段但唯一的值)。

當(dāng)客戶端下次訪問該服務(wù)端時(shí),它將cookie傳遞給服務(wù)端,服務(wù)端得到cookie,根據(jù)該cookie的value去服務(wù)端的Session數(shù)據(jù)庫中找到該value對(duì)應(yīng)的用戶信息。(Django中在應(yīng)用的setting.py中配置Session數(shù)據(jù)庫)。

根據(jù)以上描述,我們知道Session把用戶的敏感信息都保存到了服務(wù)端數(shù)據(jù)庫中,這樣具有較高的安全性。

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ù)庫了。這個(gè)在setting.py中配置:(注意我這里數(shù)據(jù)庫用的mongodb,并使用了django_mongoengine庫;關(guān)于這個(gè)配置請根據(jù)自己使用的數(shù)據(jù)庫進(jìn)行選擇,具體配置可參考官方教程)

SESSION_ENGINE = 'django_mongoengine.sessions'

SESSION_SERIALIZER = 'django_mongoengine.sessions.BSONSerializer'

views.py

# 編寫裝飾器檢查用戶是否登錄
def check_login(func):
 def inner(request, *args, **kwargs):
 next_url = request.get_full_path()
 # 獲取session判斷用戶是否已登錄
 if request.session.get('is_login'):
  # 已經(jīng)登錄的用戶...
  return func(request, *args, **kwargs)
 else:
  # 沒有登錄的用戶,跳轉(zhuǎn)剛到登錄頁面
  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ì)用戶進(jìn)行驗(yàn)證
 if username == 'aaa' and passwd == '123':
  # 進(jìn)行邏輯處理,比如保存用戶與密碼到數(shù)據(jù)庫

  # 若要使用記住密碼功能,可保存用戶名、密碼到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)證失敗,請重新嘗試'
  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>請使xxx賬戶登錄</h1>
  <div>
  <input id="user" type="text" class="form-control" name="username" placeholder="用戶" 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>

總的來看,session也是利用了cookie,通過cookie生成的value的唯一性,從而在后端數(shù)據(jù)庫session表中找到這value對(duì)應(yīng)的數(shù)據(jù)。session的用法可以保存更多的用戶信息,并使這些信息不易被暴露。

總結(jié)

session和cookie都能實(shí)現(xiàn)記住用戶登錄狀態(tài)的功能,如果為了安全起見,還是使用session更合適

以上這篇Django Session和Cookie分別實(shí)現(xiàn)記住用戶登錄狀態(tài)操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python數(shù)據(jù)類型相互轉(zhuǎn)換

    Python數(shù)據(jù)類型相互轉(zhuǎn)換

    當(dāng)涉及數(shù)據(jù)類型轉(zhuǎn)換時(shí),Python提供了多種內(nèi)置函數(shù)來執(zhí)行不同類型之間的轉(zhuǎn)換,本文主要介紹了Python數(shù)據(jù)類型相互轉(zhuǎn)換,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-09-09
  • 深入探討opencv圖像矯正算法實(shí)戰(zhàn)

    深入探討opencv圖像矯正算法實(shí)戰(zhàn)

    在機(jī)器視覺中,對(duì)于圖像的處理有時(shí)候因?yàn)榉胖玫脑驅(qū)е翿OI區(qū)域傾斜,這個(gè)時(shí)候我們會(huì)想辦法把它糾正為正確的角度視角來,本文主要介紹了opencv圖像矯正算法,感興趣的可以了解一下
    2021-05-05
  • Python的Web框架Django介紹與安裝方法

    Python的Web框架Django介紹與安裝方法

    這篇文章介紹了Python的Web框架Django與安裝方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • Python中使用Chaco繪圖庫

    Python中使用Chaco繪圖庫

    這篇文章主要介紹了Python中使用Chaco繪圖庫,Chaco是一個(gè)2D的繪圖庫,如果你安裝了Python(x,y)的話,可以在pythonxy的安裝目錄下的找到Chaco的demo程序,Chaco提供了類似Matlab和pylab的繪圖方式,我們稱之為面向腳本的繪圖方式
    2023-11-11
  • 用Python做一個(gè)久坐提醒小助手的示例代碼

    用Python做一個(gè)久坐提醒小助手的示例代碼

    這篇文章主要介紹了用Python做一個(gè)久坐提醒小助手的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-02-02
  • python+selenium實(shí)現(xiàn)QQ郵箱自動(dòng)發(fā)送功能

    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按條件批量刪除TXT文件行工具

    Python按條件批量刪除TXT文件行工具

    這篇文章主要為大家詳細(xì)介紹了Python如何實(shí)現(xiàn)按條件批量刪除TXT文件中行的工具,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-12-12
  • 基于Python爬取京東雙十一商品價(jià)格曲線

    基于Python爬取京東雙十一商品價(jià)格曲線

    這篇文章主要介紹了基于Python爬取雙十一商品價(jià)格曲線,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-10-10
  • Python多線程入門學(xué)習(xí)

    Python多線程入門學(xué)習(xí)

    這篇文章主要介紹了Python多線程入門學(xué)習(xí),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2021-12-12
  • 深入理解Python虛擬機(jī)中字典(dict)的實(shí)現(xiàn)原理及源碼剖析

    深入理解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

最新評(píng)論

凌源市| 和林格尔县| 义乌市| 深泽县| 宁陵县| 蓝田县| 龙泉市| 大英县| 房山区| 常熟市| 军事| 蒲城县| 黄骅市| 天气| 灵武市| 吉木萨尔县| 浑源县| 耿马| 宜兰市| 云林县| 岳池县| 武冈市| 南康市| 民丰县| 子洲县| 平乐县| 静安区| 革吉县| 石城县| 巴青县| 霍山县| 宝坻区| 福建省| 出国| 武义县| 德昌县| 西乌珠穆沁旗| 托克逊县| 江孜县| 义乌市| 固镇县|