Django的request請求需要首先經過中間件處理,再通過URL查找到對應的views函數進行處理。在settings的MIDDLEWARE_CLASSES中添加設置中間件進行激活,大致原理如下圖所示:
在使用Django框架進行開發的過程中,遇到一個問題:要求對覺得多數頁面請求request進行用戶登錄驗證,如果用戶沒有登錄則跳轉回到登錄頁面;如果用戶登錄了,則直接跳轉到新的鏈接頁面?
在django中提供了一種自定義裝飾器@login_required來實現驗證用戶登錄:
1 # coding: utf-8 2 from django.shortcuts import render 3 from django.contrib.auth.decorators import login_required 4 5 @login_required 6 def home(request): 7 return render(request, 'home.html')
但是這種方式有一個不方便的地方:如果每添加一個功能需要驗證登錄,就需要添加@login_required來進行裝飾。如果有大量的功能需要進行登錄驗證,工作量會增大。或者如果因為需求變化,刪除裝飾器,這種工作量會比較麻煩。
所以在學習過程中,想到使用django的中間件來進行登錄驗證,在settings中增加參數,排除不需要登錄的url,如:
EXCLUDE_URL = ( '/login/', '/logout', )
然后再創建一個中間件模塊,將此中間件添加到MIDDLEWARE_CLASSES中,定義process_request函數,對登錄的url進行驗證:
# coding: utf-8 from djangoMiddleware.settings import EXCLUDE_URL from django.shortcuts import HttpResponseRedirect import re exclued_path = [re.compile(item) for item in EXCLUDE_URL] class PubAuthMiddleWare: def process_request(self, request): url_path = request.path for each in exclued_path: if re.match(each, url_path): return if request.user.is_authenticated: return HttpResponseRedirect('/logout') else: return
其中的exclude_path為不需要驗證登錄的url,直接return進入響應的views.fun進行處理。
Django的中間件是很方便的,當需要對所有的request進行相同的處理時,可以使用中間件進行處理,很方便。