亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

簡介

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

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

Cookie

說明

Cookie是一段小信息(數(shù)據(jù)格式一般是類似key-value的鍵值對),由服務(wù)器生成,并發(fā)送給瀏覽器讓瀏覽器保存(保存時間由服務(wù)端定奪)。當(dāng)瀏覽器下次訪問該服務(wù)端時,會將它保存的Cookie再發(fā)給服務(wù)器,從而讓服務(wù)器根據(jù)Cookie知道是哪個瀏覽器或用戶在訪問它。(由于瀏覽器遵從的協(xié)議,它不會把該服務(wù)器的Cookie發(fā)送給另一個不同host的服務(wù)器)。

Django中實現(xiàn)Cookie

from django.shortcuts import render, redirect

# 設(shè)置cookie
"""
key: cookie的名字
value: cookie對應(yīng)的值
max_age: cookie過期的時間
"""
response.set_cookie(key, value, max_age)
# 為了安全,有時候我們會調(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)

下面就是具體的代碼實現(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")

 # 對用戶進(jì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小時后cookie過期
  response.set_signed_cookie("login", 'yes', salt="SSS", max_age=60*60*12)
  return response
 else:
  # 登錄失敗,則返回失敗提示到登錄頁面
  error_msg = '登錄驗證失敗,請重新嘗試'
  return render(request, "app/login.html", {
  'login_error_msg': error_msg,
  'next_url': next_url,
  })
 # 用戶剛進(jìn)入登錄頁面時,獲取到跳轉(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è)置cookie,用戶訪問其他頁面時進(jìn)行cookie驗證,用戶登出時刪除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)行驗證的一種方式。但它卻依賴于cookie。具體的過程是:服務(wù)端給每個客戶端(即瀏覽器)設(shè)置一個cookie(從上面的cookie我們知道,cookie是一種”key, value“形式的數(shù)據(jù),這個cookie的value是服務(wù)端隨機(jī)生成的一段但唯一的值)。

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

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

Django中Session的實現(xiàn)

# 設(shè)置session數(shù)據(jù), key是字符串,value可以是任何值
request.session[key] = value
# 獲取 session
request.session.get[key]
# 刪除 session中的某個數(shù)據(jù)
del request.session[key]
# 清空session中的所有數(shù)據(jù)
request.session.delete()

下面就是具體的代碼實現(xiàn)了:

首先就是設(shè)置保存session的數(shù)據(jù)庫了。這個在setting.py中配置:(注意我這里數(shù)據(jù)庫用的mongodb,并使用了django_mongoengine庫;關(guān)于這個配置請根據(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)

 # 對用戶進(jì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 = '登錄驗證失敗,請重新嘗試'
  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對應(yīng)的數(shù)據(jù)。session的用法可以保存更多的用戶信息,并使這些信息不易被暴露。

總結(jié)

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

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

相關(guān)文章

  • Flask使用SQLAlchemy實現(xiàn)持久化數(shù)據(jù)

    Flask使用SQLAlchemy實現(xiàn)持久化數(shù)據(jù)

    本文主要介紹了Flask使用SQLAlchemy實現(xiàn)持久化數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-07-07
  • python基礎(chǔ)學(xué)習(xí)之如何對元組各個元素進(jìn)行命名詳解

    python基礎(chǔ)學(xué)習(xí)之如何對元組各個元素進(jìn)行命名詳解

    python的元祖和列表類似,不同之處在于元祖的元素不能修改,下面這篇文章主要給大家介紹了關(guān)于python基礎(chǔ)學(xué)習(xí)之如何對元組各個元素進(jìn)行命名的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2018-07-07
  • pycharm解決關(guān)閉flask后依舊可以訪問服務(wù)的問題

    pycharm解決關(guān)閉flask后依舊可以訪問服務(wù)的問題

    這篇文章主要介紹了pycharm解決關(guān)閉flask后依舊可以訪問服務(wù)的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • Python通過OpenPyXL處理Excel的完整教程

    Python通過OpenPyXL處理Excel的完整教程

    OpenPyXL是一個強(qiáng)大的Python庫,用于處理Excel文件,允許讀取、編輯和創(chuàng)建Excel工作簿和工作表,本文將詳細(xì)介紹OpenPyXL的各種功能,希望對大家有所幫助
    2023-11-11
  • 詳解Django中CSRF和CORS的區(qū)別

    詳解Django中CSRF和CORS的區(qū)別

    本文主要介紹了詳解Django中CSRF和CORS的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • python中datetime模塊中strftime/strptime函數(shù)的使用

    python中datetime模塊中strftime/strptime函數(shù)的使用

    這篇文章主要介紹了python中datetime模塊中strftime/strptime函數(shù)的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-07-07
  • Python實現(xiàn)地圖可視化案例詳解

    Python實現(xiàn)地圖可視化案例詳解

    ?Python的地圖可視化庫很多,Matplotlib庫雖然作圖很強(qiáng)大,但只能做靜態(tài)地圖。而我今天要講的是交互式地圖庫,分別為pyecharts、folium。感興趣的可以學(xué)習(xí)一下
    2022-01-01
  • Python?numpy生成矩陣基礎(chǔ)用法實例代碼

    Python?numpy生成矩陣基礎(chǔ)用法實例代碼

    矩陣是matrix類型的對象,該類繼承自numpy.ndarray,任何針對ndarray的操作,對矩陣對象同樣有效,下面這篇文章主要給大家介紹了關(guān)于Python?numpy生成矩陣基礎(chǔ)的相關(guān)資料,需要的朋友可以參考下
    2022-08-08
  • Python使用Cv2模塊識別驗證碼的操作方法

    Python使用Cv2模塊識別驗證碼的操作方法

    這篇文章主要介紹了Python使用Cv2模塊識別驗證碼,使用Cv2模塊、pytesseract模塊進(jìn)行操作,pytesseract模塊將智能識別圖片字體數(shù)字,用于打印出來,本文通過代碼案例給大家詳細(xì)講解,需要的朋友可以參考下
    2023-01-01
  • Python 多線程之threading 模塊的使用

    Python 多線程之threading 模塊的使用

    這篇文章主要介紹了Python 多線程之threading 模塊的使用,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下
    2021-04-04

最新評論