中間件和auth模塊

中間件

1.什麼是中間件

中間件顧名思義,是介於requestresponse處理之間的一道處理過程,相對比較輕量級,而且在全局上改變django的輸入與輸出。由於改變的是全局,因此須要謹慎實用,用很差會影響到性能 

2.中間件的做用

若是你想修改請求,例如被傳送到view中的HttpRequest對象。 或者你想修改view返回的HttpResponse對象,這些均可以經過中間件來實現。 可能你還想在view執行以前作一些操做,這種狀況就能夠用 middleware來實現。 Django默認的中間件:(在django項目的settings模塊中,有一個 MIDDLEWARE_CLASSES 變量,其中每個元素就是一箇中間件) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] 

3.自定義中間件

from django.utils.deprecation import MiddlewareMixin class MyMiddle(MiddlewareMixin): def process_request(self, request): # request時觸發 print('middle request') def process_response(self, request, response): # response時觸發 print('process_response') return response def process_view(self, request, callback, callback_args, callback_kwargs): # 路由到視圖函數之間觸發 print('process_view') # callback(request) def process_exception(self, request, exception): # 報錯時觸發 return HttpResponse(exception) def process_template_response(self, request, response): # return views.類()時觸發 print('i am process_template_response') print(response) return views.Test()

4.中間件應用場景

1.作IP訪問頻率限制 某些IP訪問服務器的頻率太高,進行攔截,好比限制每分鐘不能超過20次。 2.URL訪問過濾 若是用戶訪問的是login視圖(放過) 若是訪問其餘視圖,須要檢測是否是有session認證,已經有了放行, 沒有返回login,這樣就免得在多個視圖函數上寫裝飾器了! 

5.CSRF_TOKEN跨站請求僞造

在form表單中應用:
<form action="" method="post"> {% csrf_token %} <p>用戶名:<input type="text" name="name"></p> <p>密碼:<input type="text" name="password"></p> <p><input type="submit"></p> </form> 
在Ajax中應用:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="/static/jquery-3.3.1.js"></script> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} <p>用戶名:<input type="text" name="name"></p> <p>密碼:<input type="text" name="password" id="pwd"></p> <p><input type="submit"></p> </form> <button class="btn">點我</button> </body> <script> $(".btn").click(function () { $.ajax({ url: '', type: 'post', data: { 'name': $('[name="name"]').val(), 'password': $("#pwd").val(), 'csrfmiddlewaretoken': $('[name="csrfmiddlewaretoken"]').val() }, success: function (data) { console.log(data) } }) }) </script> </html> 
全站禁用

註釋掉中間件 'django.middleware.csrf.CsrfViewMiddleware',javascript

局部禁用
FBVfrom django.views.decorators.csrf import csrf_exempt,csrf_protect # 再也不檢測,局部禁用(前提是全站使用) # @csrf_exempt # 檢測,局部使用(前提是全站禁用) # @csrf_protect def csrf_token(request): if request.method=='POST': print(request.POST) return HttpResponse('ok') return render(request,'csrf_token.html') 
CBVfrom django.views import View from django.views.decorators.csrf import csrf_exempt,csrf_protect from django.utils.decorators import method_decorator @method_decorator(csrf_exempt,name='dispatch') class Foo(View): def dispatch(self, request, *args, **kwargs): res = super().dispatch(request, *args, **kwargs) return res def get(self,request): pass def post(self,request): pass 

Auth模塊

1.Auth模塊經常使用方法

from django.contrib import auth authenticate(request, username=name, password=pwd) 用戶認證功能,返回一個 User 對象 login(request, user) 在後端爲該用戶生成相關session數據 logout(request) 當前請求的session信息會所有清除 is_authenticated() 判斷當前請求是否經過了認證 login_requierd() 裝飾器,某個視圖添加登陸校驗 該裝飾器須要在settings中添加登陸地址 LOGIN_URL = '/login/' # 這裏配置成你項目登陸頁面的路由 create_user() 建立新用戶 create_superuser() 建立新的超級用戶 check_password(password) 提供的一個檢查密碼是否正確的方法 set_password(password) 修改密碼,設置完必定要調用用戶對象的save方法 

2.User對象的屬性

User對象屬性:username, password is_staff 用戶是否擁有網站的管理權限. is_active 是否容許用戶登陸, 設置爲 False,能夠在不刪除用戶的前提下禁止用戶登陸。 

3.擴展默認的auth_user表

modelfrom django.contrib.auth.models import AbstractUser class UserInfo(AbstractUser): # 繼承父類,並派生新須要的字段 nid = models.AutoField(primary_key=True) phone = models.CharField(max_length=11, null=True, unique=True) def __str__(self): return self.username 注意,須要在setting中添加AUTH_USER_MODEL = "app名.UserInfo"
相關文章
相關標籤/搜索