django的auth認(rèn)證,authenticate和裝飾器功能詳解
在django中創(chuàng)建表,會(huì)自動(dòng)創(chuàng)建一些django自帶的表,先了解用戶(hù)認(rèn)證,
認(rèn)證登錄 先要引用 ,
from django.contrib import auth
有很多方法,
網(wǎng)站先有登錄和認(rèn)證,
authenticate(),提供用戶(hù)認(rèn)證,驗(yàn)證用戶(hù)名和密碼是否正確,一般需要username ,password兩個(gè)關(guān)鍵字參數(shù),
認(rèn)證信息有效,返回有一個(gè)User對(duì)象。authrenticate()會(huì)在User對(duì)象上設(shè)置一個(gè)屬性標(biāo)識(shí),認(rèn)證了該用戶(hù),
創(chuàng)建一個(gè)Book表,然后生成數(shù)據(jù)庫(kù)
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里命令臺(tái)terminal 里創(chuàng)建一個(gè)超級(jí)用戶(hù) 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頁(yè)面,
<!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)我提交的時(shí)候,會(huì)出現(xiàn)forbidden的情況,get請(qǐng)求不會(huì)出現(xiàn)這種情況,
因?yàn)樵趕etting文件的中間件,不允許出現(xiàn)跨站請(qǐng)求,
別的網(wǎng)站第一次訪問(wèn)我就發(fā)送post 請(qǐng)求,我的網(wǎng)站就拒絕,怎么拒絕,要區(qū)分第一次和第二次,y用cookie, 在cookie里加上csrf-token,下次請(qǐng)求時(shí),cookie就有csrf-token ,就知道,已經(jīng)登錄過(guò)了,不會(huì)再被forbidden掉了,
在form表單中添加 {% csrf_token %},
在前端頁(yè)面,檢查元素,就可以看到有了crsf-token ,是隱藏的狀態(tài),
------
在ajax請(qǐng)求的時(shí)候,也要加上csrf-token,
$.ajax({ data:{csrfmiddlewaretoken:'{{csrf-token}}' }, }),
-----
在views文件,使用authenticate()方法,從前端獲取用戶(hù)登錄的信息進(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")
在前端頁(yè)面,輸入剛才注冊(cè)的超級(jí)用戶(hù),和密碼,登錄成功,后臺(tái)進(jìn)行打印出用戶(hù)名和密碼,
user root pwd root123456 [05/Dec/2017 10:04:41] "POST /login/ HTTP/1.1" 200 2
但現(xiàn)在存在一個(gè)問(wèn)題,沒(méi)有cookie和session,如果換個(gè)瀏覽器,登錄index頁(yè)面,還是能直接直接登錄,
所以現(xiàn)在就可以直接用,login(request,User),就相當(dāng)于設(shè)置了cookie和session, 在跳轉(zhuǎn)到index頁(yè)面親,跳轉(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:#如果有這個(gè)用戶(hù),跳轉(zhuǎn)到index頁(yè)面 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個(gè)方法, #authenticate() #login(HttpResquest,user) #logout(request) # @login_required,與is_authenticate 的功能一樣,就不用判斷, #舉例說(shuō)明 @login_required def index2(request): # 可以加一個(gè)裝飾器,與is_authenticated()的功能一樣,@login_required # 先導(dǎo)入 from django.contrib.auth.decorators import login_required return render(request,"index.html") #如果用戶(hù)沒(méi)有登錄,者跳轉(zhuǎn)到django默認(rèn)的登錄URL"accounts/login/" ,可以以 #通過(guò)settings文件通過(guò)LOGIN_URL進(jìn)行修改,并傳遞當(dāng)前訪問(wèn)的url的絕對(duì)路徑 def index(request): #打印一個(gè)user對(duì)象,利用user對(duì)象的is_tuthenticated方法做判斷,是否驗(yàn)證過(guò),返回布爾值,,做判斷 #用戶(hù)登錄后才能訪問(wèn)某些頁(yè)面, #沒(méi)有登錄就訪問(wèn),就直接跳到登錄頁(yè)面, #用戶(hù)跳轉(zhuǎn)到登錄頁(yè)面完成登錄,自動(dòng)訪問(wèn)跳轉(zhuǎn)到之前訪問(wèn)的地址, print("=====>",request.user.is_authenticated()) #=====> root # ,如果換個(gè)瀏覽器,就是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()方法,得到一個(gè)User對(duì)象,做user驗(yàn)證, user = auth.authenticate(username=user,password=pwd) print("user",user) print("pwd",pwd) if user is not None:#如果有這個(gè)用戶(hù),跳轉(zhuǎn)到index頁(yè)面 auth.login(request,user)#auth下的login() 方法,就相當(dāng)于session+cookie,在跳轉(zhuǎn)到index頁(yè)面還要實(shí)現(xiàn)做判斷, return redirect("/index/") return render(request,"log_in.html")
-------------------------------
現(xiàn)在寫(xiě)一個(gè)注冊(cè)功能,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), ]
再寫(xiě)一個(gè)reg頁(yè)面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>注冊(cè)頁(yè)面</h1> <h4>{{ error_message }}</h4> <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ù)中,
#注冊(cè)頁(yè)面 def reg(request): error_message = ""#放在全局 if request.method=="POST": #獲取用戶(hù)輸入的數(shù)據(jù),存到數(shù)據(jù)庫(kù)前,要先判斷 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="用戶(hù)名不能為空" elif repeat_pwd != pwd: error_message = "密碼不一致" elif User.objects.filter(username = user): error_message = "用戶(hù)已存在" else: #把用戶(hù)輸入的用戶(hù)名和密碼存到數(shù)據(jù)庫(kù),但django做了一次加密, #所以就不能直接用,create的方法,要用User表的方法,create_user() User.objects.create_user(username = user,password = pwd) #注冊(cè)成功后,跳到登錄頁(yè)面 return redirect("/log_in/") return render(request,"reg.html",{"error_message":error_message})
auth下的注銷(xiāo)功能,直接挑用logout()方法,
#注銷(xiāo)功能,清除掉cookie和session, def log_out(request): #登錄的時(shí)候,用到了login()函數(shù), auth.logout(request)#清除了cookie和session,清除了當(dāng)前的用戶(hù), return redirect("/log_in/")
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
在Python中將函數(shù)作為另一個(gè)函數(shù)的參數(shù)傳入并調(diào)用的方法
今天小編就為大家分享一篇在Python中將函數(shù)作為另一個(gè)函數(shù)的參數(shù)傳入并調(diào)用的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01python實(shí)現(xiàn)人性化顯示金額數(shù)字實(shí)例詳解
在本篇內(nèi)容里小編給大家整理了關(guān)于python實(shí)現(xiàn)人性化顯示金額數(shù)字實(shí)例內(nèi)容,需要的朋友們可以參考下。2020-09-09Python批量將csv文件轉(zhuǎn)化成xml文件的實(shí)例
將 csv 格式轉(zhuǎn)換成xml格式有許多方法,可以用數(shù)據(jù)庫(kù)的方式,也有許多軟件可以將 csv 轉(zhuǎn)換成xml。但是比較麻煩,本文利用 Python 一鍵批量將 csv 文件轉(zhuǎn)化成 xml 文件。2021-05-05詳解pandas.DataFrame.plot() 畫(huà)圖函數(shù)
這篇文章主要介紹了詳解pandas.DataFrame.plot()畫(huà)圖函數(shù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06