Django框架之中間件與Auth模塊
一 cbv加裝飾器
-先導入:from django.utils.decorators import method_decorator
-1 能夠在方法上加裝飾器:
@method_decorator(login_auth)
-2 能夠在類上加
@method_decorator(login_auth,name='post')
@method_decorator(login_auth,name='get')
-3 能夠加在dishpatch方法上
@method_decorator(login_auth)
一旦加在dishpatch,說明,全部方法都加了裝飾器
二 中間件
-中間件是什麼?請求和響應之間的一道屏障
-中間件做用:控制請求和響應
-django中內置幾個中間件
-自定義中間件
-from django.utils.deprecation import MiddlewareMixin 先導入
-定義一個類,隨意命名,繼承MiddlewareMixin
class MyMiddleware1(MiddlewareMixin):
def process_request(self, request):
print('MyMiddleware---->1---->process_request')
# 返回HttpRspons對象,直接返回,走本身的process_response
# 返回None的時候,繼續往下走
# return HttpResponse('i am middle--1')
return None
def process_response(self, request, response):
print('MyMiddleware--->1---->process_response')
return response
-使用:在setting中註冊,是有順序的,
MIDDLEWARE = [
'app01.mymiddelware.MyMiddleware1',]
-中間件執行順序:
-process_request,從上往下執行
-若是retrun HttpResponse的對象,直接返回了
-若是retrun None ,繼續往下走
-process_response,從下往上執行
-必需要retrun Httpresponse的對象
-中間件的方法:()
-process_request
-請求來的時候,會響應它
-process_response
-響應回去的時候,會走它
-process_view(瞭解)
- request, callback(視圖函數), callback_args(無名分組的參數), callback_kwargs(有名分組的參數)
-執行順序,詳見圖
-def process_exception(self, request, exception)(瞭解)
-def process_template_response(self, request, response):(瞭解)
三 csrf:跨站請求僞造
好比:轉帳請求:transfer?to=lqz&count=1000
-是什麼?攻擊者盜用了你的身份,以你的名義發送惡意請求,對服務器來講這個請求是徹底合法的
-如何防範:
-經過refer
-加一個隨機字符串校驗(加載請求的路徑裏,加載請求體中)
-在請求頭中加字符串校驗
django中的應用:
-中間件不註釋掉
-之後再發post請求,攜帶那個隨機字符串
-form表單形式:
<form action="" method="post">
{% csrf_token %}
<input type="text" name="name">
<input type="text" name="pwd">
<input type="submit" value="提交">
</form>
-ajax提交
data: {
'name': $('[name="name"]').val(),
'pwd': $('[name="pwd"]').val(),
//'csrfmiddlewaretoken': $('[name="csrfmiddlewaretoken"]').val()
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
csrf:局部禁用,局部使用
-用裝飾器:from django.views.decorators.csrf import csrf_exempt,csrf_protect
-fbv--->直接加載fbv上就好了
-局部禁用,全局得使用
@csrf_exempt
def csrf_disable(request):
print(request.POST)
return HttpResponse('ok')
-局部使用,全局得禁用
@csrf_protect
def csrf_disable(request):
print(request.POST)
return HttpResponse('ok')
-cbv-->只能加在dispatch方法或者類上面
-局部禁用,全局得使用
-局部使用,全局得禁用
from django.views import View
from django.utils.decorators import method_decorator
@method_decorator(csrf_protect,name='dispatch')
class Csrf_disable(View):
# @method_decorator(csrf_protect)
def dispatch(self, request, *args, **kwargs):
ret=super().dispatch(request, *args, **kwargs)
return ret
def get(self,request):
return HttpResponse('ok')
def post(self,request): return HttpResponse('post---ok') 四 auth組件 -auth是什麼? -django內置的用戶認證系統,能夠快速的實現,登陸,註銷,修改密碼.... -怎麼用? -(1)先建立超級用戶: -python3 manage.py createsuperuser -輸入用戶名,郵箱(能夠不輸入),密碼,敲回車,這樣就建立出一個超級用戶 -也就是在auth_user這個表中插入了一條數據(密碼是加密的,因此我不能手動插入) -(2)驗證用戶: -from django.contrib import auth -user = auth.authenticate(request, username=name, password=pwd) -至關於在查詢:user=models.User.objects.filter(name=name,pwd=pwd).first() -若是校驗經過,會返回一個user對象,經過判斷user對象,校驗是否驗證成功 -(3)登陸 -auth.login(request,user) -其實就是在session中寫了一條數據 -(4)一旦登陸成功,調了這個函數login(request,user) -之後再視圖類,函數中的request對象中,就有一個user對象,就是當前登陸的用戶對象 -若是沒有登陸,request.user=AnonymousUser,匿名用戶 -(5)註銷 -auth.logout(request) -內部:調用了request.session.flush(),刪除了登陸狀態 -(6)登陸認證裝飾器 -from django.contrib.auth.decorators import login_required -@login_required(redirect_field_name='eee',login_url='/login/') -redirect_field_name:修改?後面的key值, -login_url:若是沒有登陸,跳轉到的頁面 -能夠局部配置 -能夠全局配置(在setting中) # 全局的配置,若是沒有登陸,跳到這個路由 LOGIN_URL='/login/' -(7)建立用戶: -from django.contrib.auth.models import User - 建立超級用戶和普通用戶 # 不能用create # user=User.objects.create(username=name,password=pwd) # 建立超級用戶 # user=User.objects.create_superuser(username=name,password=pwd) # 建立普通用戶 user=User.objects.create_user(username=name,password=pwd) -(8)校驗密碼 -request.user.check_password(pwd) -先拿到用戶(能夠是登陸用戶,能夠現查) -(9)修改密碼: -user.set_password(pwd) -user.save() -注意:必定要調用save(),不然是不保存的 -(10)is_authenticated() -若是經過驗證,是true反之false -(11)其餘方法(瞭解): -is_active:禁止登陸網站(用戶還存在,封號) -is_staff:是否對網站有管理權限(能不能登陸admin) -(12)刪除用戶 -orm刪除 若是想在認證組件上加手機號等其餘字段:如何處理 -(1) 定義一個表模型,跟User一對一管理 class UserDetail(models.Model): phone=models.CharField(max_length=32) # 一對一跟auth_user表作關聯 # 若是是從外部引入的表模型,是不能加引號的 # 若是加引號,只是在當前model找 user=models.OneToOneField(to=User) -(2)定義一個表模型,繼承(AbstractUser) -from django.contrib.auth.models import AbstractUser class UserInfo(AbstractUser): # username,password...都有 phone=models.CharField(max_length=32) sex=models.BooleanField() -在setting中配置: AUTH_USER_MODEL ='app01.UserInfo' -作數據庫遷移,之後就沒有auth_user這個表了,之後認證組件用的表就是UserInfo -原來auth中的其餘操做: -authentication -login -logout -set_password .... ---同樣用,徹底同樣 -不同的地方: 若是以前用到User這個表模型的地方,都換成UserInfo 博客項目: 1 需求分析 -首頁(顯示文章) -文章詳情 -點贊,點踩 -文章評論 -字評論 -評論的展現 -登陸功能(圖片驗證碼) -註冊功能(基於form驗證,ajax) -我的站點(不一樣人不一樣樣式,文章過濾) -後臺管理: -文章展現 -新增文章 -富文本編輯器 2 設計程序(框架,數據庫設計) -UserInfo----用戶表 -blog-----我的站點表 -Article----文章表 -commit----評論表 -upanddown----點贊點踩表 -category---文章分類表 -tag---文章標籤表 -表關係 -userInfo跟blog ---- 一對一 -article跟blog-----一對多 -article跟category----(一篇文章只能由一個分類,一個分類下有多篇文章)一對多 -article跟tag----(一個標籤能夠對應多篇文章,一篇文章能夠有多個標籤)多對多 -commit跟Article---- 一對多 -upanddown跟Article---- 一對多 -user跟commit---一對多 -user跟upanddown---一對多 -category跟blog----一對多 -tag跟blog----一對多 3 分任務開發(git) 4 測試