您好,登錄后才能下訂單哦!
這篇文章主要介紹了django中auth認(rèn)證、authenticate和裝飾器功能的示例分析,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
在django中創(chuàng)建表,會自動創(chuàng)建一些django自帶的表,先了解用戶認(rèn)證,
認(rèn)證登錄 先要引用 ,
from django.contrib import auth
有很多方法,
網(wǎng)站先有登錄和認(rèn)證,
authenticate(),提供用戶認(rèn)證,驗(yàn)證用戶名和密碼是否正確,一般需要username ,password兩個關(guān)鍵字參數(shù),
認(rèn)證信息有效,返回有一個User對象。authrenticate()會在User對象上設(shè)置一個屬性標(biāo)識,認(rèn)證了該用戶,
創(chuàng)建一個Book表,然后生成數(shù)據(jù)庫
from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=32) price = models.DecimalField(max_digits=5,decimal_places=2)
在pycharm里命令臺terminal 里創(chuàng)建一個超級用戶 root, 密碼 root123456
C:\Users\lenovo\PycharmProjects\auth_gu>python manage.py createsuperuser Username (leave blank to use 'lenovo'): root Email address: Password: Password (again): This password is too short. It must contain at least 8 characters. Password: Password (again): Superuser created successfully.
然后在auth_user 表中就有了剛才創(chuàng)建的信息
可以看到django是做了一層加密,
創(chuàng)建login頁面,
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="post"> {# #} {% csrf_token %} <p>姓名:<input type="text" name="user"></p> <p>密碼:<input type="password" name="pwd"></p> <input type="submit" value="提交"> </form> </body> </html>
當(dāng)我提交的時候,會出現(xiàn)forbidden的情況,get請求不會出現(xiàn)這種情況,
因?yàn)樵趕etting文件的中間件,不允許出現(xiàn)跨站請求,
別的網(wǎng)站第一次訪問我就發(fā)送post 請求,我的網(wǎng)站就拒絕,怎么拒絕,要區(qū)分第一次和第二次,y用cookie, 在cookie里加上csrf-token,下次請求時,cookie就有csrf-token ,就知道,已經(jīng)登錄過了,不會再被forbidden掉了,
在form表單中添加 {% csrf_token %},
在前端頁面,檢查元素,就可以看到有了crsf-token ,是隱藏的狀態(tài),
------
在ajax請求的時候,也要加上csrf-token,
$.ajax({ data:{csrfmiddlewaretoken:'{{csrf-token}}' }, }),
-----
在views文件,使用authenticate()方法,從前端獲取用戶登錄的信息進(jìn)行驗(yàn)證,
def login(request): if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") #使用authenticate()方法 auth.authenticate(username=user,password=pwd) print("user",user) print("pwd",pwd) return HttpResponse("ok") return render(request,"login.html")
在前端頁面,輸入剛才注冊的超級用戶,和密碼,登錄成功,后臺進(jìn)行打印出用戶名和密碼,
user root pwd root123456 [05/Dec/2017 10:04:41] "POST /login/ HTTP/1.1" 200 2
但現(xiàn)在存在一個問題,沒有cookie和session,如果換個瀏覽器,登錄index頁面,還是能直接直接登錄,
所以現(xiàn)在就可以直接用,login(request,User),就相當(dāng)于設(shè)置了cookie和session, 在跳轉(zhuǎn)到index頁面親,跳轉(zhuǎn)
修改login函數(shù),因?yàn)榕cdjango里login()重名了,
def index(request): return render(request,'index.html') #用django的認(rèn)證方法, def log_in(request): if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") #使用authenticate()方法 auth.authenticate(username=user,password=pwd) print("user",user) print("pwd",pwd) if user is not None:#如果有這個用戶,跳轉(zhuǎn)到index頁面 auth.login(request,user) ------------------- return redirect("/index/") return render(request,"log_in.html")
關(guān)于裝飾器login_required 和is_authenticated ()的功能一樣,就是不用判斷了
from django.shortcuts import render,HttpResponse,redirect from django.contrib.auth.decorators import login_required #與is_authenticate的工程一樣, # Create your views here. from django.contrib import auth #auth 的3個方法, #authenticate() #login(HttpResquest,user) #logout(request) # @login_required,與is_authenticate 的功能一樣,就不用判斷, #舉例說明 @login_required def index2(request): # 可以加一個裝飾器,與is_authenticated()的功能一樣,@login_required # 先導(dǎo)入 from django.contrib.auth.decorators import login_required return render(request,"index.html") #如果用戶沒有登錄,者跳轉(zhuǎn)到django默認(rèn)的登錄URL"accounts/login/" ,可以以 #通過settings文件通過LOGIN_URL進(jìn)行修改,并傳遞當(dāng)前訪問的url的絕對路徑 def index(request): #打印一個user對象,利用user對象的is_tuthenticated方法做判斷,是否驗(yàn)證過,返回布爾值,,做判斷 #用戶登錄后才能訪問某些頁面, #沒有登錄就訪問,就直接跳到登錄頁面, #用戶跳轉(zhuǎn)到登錄頁面完成登錄,自動訪問跳轉(zhuǎn)到之前訪問的地址, print("=====>",request.user.is_authenticated()) #=====> root # ,如果換個瀏覽器,就是AnonymousUser匿名, if request.user.is_authenticated():#已登錄 return render(request,"index.html") else: return redirect("/log_in/") #登錄之前先驗(yàn)證, return render(request,'index.html') #用django的認(rèn)證方法, def log_in(request): if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") #使用authenticate()方法,得到一個User對象,做user驗(yàn)證, user = auth.authenticate(username=user,password=pwd) print("user",user) print("pwd",pwd) if user is not None:#如果有這個用戶,跳轉(zhuǎn)到index頁面 auth.login(request,user)#auth下的login() 方法,就相當(dāng)于session+cookie,在跳轉(zhuǎn)到index頁面還要實(shí)現(xiàn)做判斷, return redirect("/index/") return render(request,"log_in.html")
-------------------------------
現(xiàn)在寫一個注冊功能,url路由
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^log_in/', views.log_in), url(r'^index/', views.index), url(r'^reg/', views.reg), url(r'^log_out/', views.log_out), ]
再寫一個reg頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>注冊頁面</h2> <h5>{{ error_message }}</h5> <form action="/reg/" method="post"> {% csrf_token %} <p>姓名:<input type="text" name="user"></p> <p>密碼:<input type="password" name="pwd"></p> <p>確認(rèn)密碼:<input type="password" name="repeat_pwd"></p> <input type="submit"> </form> </body> </html>
在views 視圖函數(shù)中,
#注冊頁面 def reg(request): error_message = ""#放在全局 if request.method=="POST": #獲取用戶輸入的數(shù)據(jù),存到數(shù)據(jù)庫前,要先判斷 user = request.POST.get("user") pwd = request.POST.get("pwd") repeat_pwd = request.POST.get("repeat_pwd") #密碼不能為空, if not pwd or not repeat_pwd : error_message="密碼不能為空" elif not user : error_message="用戶名不能為空" elif repeat_pwd != pwd: error_message = "密碼不一致" elif User.objects.filter(username = user): error_message = "用戶已存在" else: #把用戶輸入的用戶名和密碼存到數(shù)據(jù)庫,但django做了一次加密, #所以就不能直接用,create的方法,要用User表的方法,create_user() User.objects.create_user(username = user,password = pwd) #注冊成功后,跳到登錄頁面 return redirect("/log_in/") return render(request,"reg.html",{"error_message":error_message})
auth下的注銷功能,直接挑用logout()方法,
#注銷功能,清除掉cookie和session, def log_out(request): #登錄的時候,用到了login()函數(shù), auth.logout(request)#清除了cookie和session,清除了當(dāng)前的用戶, return redirect("/log_in/")
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“django中auth認(rèn)證、authenticate和裝飾器功能的示例分析”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。