溫馨提示×

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

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

Python Django如何實(shí)現(xiàn)session登錄注銷過程

發(fā)布時(shí)間:2021-08-07 09:44:05 來源:億速云 閱讀:115 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要為大家展示了“Python Django如何實(shí)現(xiàn)session登錄注銷過程”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Python Django如何實(shí)現(xiàn)session登錄注銷過程”這篇文章吧。

開發(fā)工具:pycharm

簡(jiǎn)單實(shí)現(xiàn)session的登錄注銷功能

Django配置好路由分發(fā)功能

默認(rèn)session在Django里面的超時(shí)時(shí)間是兩周

使用request.session.set_expiry(60)設(shè)置超時(shí)時(shí)間,以秒為單位

在Django配置文件里配置session鏈接 https://www.jb51.net/article/166988.htm

urlpatterns = [
 path('admin/', admin.site.urls),
 path('app01/', include('app01.urls'))
]

app01/urls.py的路由如下

urlpatterns = [
 path('login/', views.login),
 path('index/', views.index),
]

app01/views.py視圖的內(nèi)容如下

# Create your views here.
from django.shortcuts import HttpResponse, render, redirect
def login(request):
 if request.method == 'GET':
  return render(request, 'login.html')
 elif request.method == 'POST':
  user = request.POST.get('username')
  pwd = request.POST.get('pwd')
  if user == 'song' and pwd == '123':
   # 往session里寫入數(shù)據(jù)的時(shí)候,Django會(huì)自動(dòng)生成隨機(jī)碼,發(fā)送給cookie,然后自己保留一份跟cookie一一對(duì)應(yīng)
   request.session['username'] = user
   request.session['is_login'] = True
   #設(shè)置session(同時(shí)對(duì)應(yīng)的cookie)超時(shí)時(shí)間,按秒計(jì)算
   request.session.set_expiry(60)
   # 路徑已經(jīng)要寫全,把/app01帶上,以前好像不帶是可以的
   return redirect('/app01/index/')
  else:
   return render(request, 'login.html')
def index(request):
 # 拿到cookie對(duì)應(yīng)的隨機(jī)碼,來查找session里的is_login字段是否True,如果通過則表示通過
 if request.session.get('is_login', None):
  return render(request, 'index.html')
 else:
  return HttpResponse('滾')
def logout(request):
 # 清除當(dāng)前對(duì)應(yīng)session所有數(shù)據(jù)
 request.session.clear()
 # 路徑已經(jīng)要寫全,把/app01帶上,以前好像不帶是可以的
 return redirect('/app01/login')

templates目錄的里login.html內(nèi)容

form表單里路徑一定要帶上/app01的路徑

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
 <div>
  <form action="/app01/login/" method="post">
   <input type="text" name="username">
   <input type="password" name="pwd">
   <input type="submit" value="提交">
  </form>
 </div>
</body>
</html>

templates目錄的里index.html內(nèi)容

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
 <h2>登錄成功</h2>
 <div>
  <a href="/app01/logout/" rel="external nofollow" rel="external nofollow" >注銷</a>
 </div>
</body>
</html>

重點(diǎn)重點(diǎn)重點(diǎn)?。?!如果出現(xiàn)已下報(bào)錯(cuò),則是因?yàn)閟ession信息要保存到數(shù)據(jù)庫中,而你的Django沒創(chuàng)建session表呢,

所以要在命令行執(zhí)行以下命令,來構(gòu)造session表

python manage.py makemigrations
python manage.py migrate

Python Django如何實(shí)現(xiàn)session登錄注銷過程

==================================分割線=======================================================

帶session信息版本的簡(jiǎn)單認(rèn)證實(shí)現(xiàn)

models.py文件內(nèi)容

from django.db import models
# Create your models here.
class UserInfo(models.Model):
 username = models.CharField(max_length=16)
 password = models.CharField(max_length=32)

urls.py文件內(nèi)容

from django.contrib import admin
from django.urls import path,include
from app01 import views
from django.conf.urls import url
urlpatterns = [
 # path('login/', views.login),
 path('index/', views.index),
 # path('logout/', views.logout),
 # path('fm/', views.fm),
 path('aa/', views.aa),
 path('select/', views.select),
]

views.py文件的內(nèi)容

# Create your views here.
from django.shortcuts import HttpResponse, render, redirect
from django.views.decorators.csrf import csrf_exempt,csrf_protect
from app01 import models
from functools import wraps
#做session驗(yàn)證的的裝飾器,
def checklogin(func):
 @wraps(func)
 def wrapper(request,*args,**kwargs):
  if request.session.get('is_login') == '1':
   return func(request,*args,**kwargs)
  else:
   return redirect('/app01/aa')
 return wrapper

def aa(requrst):
 if requrst.method == 'GET':
  print('get')
  return render(requrst, 'aa.html')
 elif requrst.method == 'POST':
  username = requrst.POST.get('username')
  pwd = requrst.POST.get('password')
  user = models.UserInfo.objects.filter(username=username,password=pwd)
  # print(type(pwd))
  # print(models.UserInfo.objects.filter(username=username).values('password'))
  if user:
   #如果輸入的賬戶名跟數(shù)據(jù)庫中的賬戶名密碼相匹配就忘session信息里寫入一條is_login的數(shù)據(jù)
   #同時(shí)隨機(jī)生成的字符串ID也寫到cookie里當(dāng)做sessionid使用
   requrst.session['is_login'] = '1'
   return redirect('/app01/index')
  return redirect('/app01/aa')

#在訪問頁面的時(shí)候先做驗(yàn)證,拿自己的cookie里的sessionid去跟服務(wù)器端的session_key做對(duì)比
#對(duì)比認(rèn)證通過就允許訪問
@checklogin
def index(request):
 return render(request,'index.html')

aa.html文件內(nèi)容

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>aa</title>
</head>
<body>
 <h2>aa頁面</h2>
 <form action="/app01/aa/" method="POST">
 {% csrf_token %}
  <p>用戶名:
 <input type="text" name="username">
  </p>
  <p>密碼:
 <input type="password" name="password">
  </p>
  <input type="submit" value="提交">
 </form>
</body>
</html>

index.html文件內(nèi)容

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
 <h2>登錄成功</h2>
 <div>
  <a href="/app01/logout/" rel="external nofollow" rel="external nofollow" >注銷</a>
 </div>
</body>
</html>

以上是“Python Django如何實(shí)現(xiàn)session登錄注銷過程”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

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

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

AI