中間件補充:
自寫的中間件要在setting裡注冊,按注冊的順序執行,
請求進來執行一次,返回響應來執行一次
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
class M1(MiddlewareMixin):
def process_request(self, request):
print("M1進來了")
# 沒有返回值,為None可以繼續往下走
return HttpResponse("無權訪問")
def process_response(self, request, response):
print("M1走了")
return response
class M2(MiddlewareMixin):
def process_request(self, request):
print("M2進來了")
def process_response(self, request, response):
print("M2走了")
return response
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',
'app03_phone_number_management.middleware.auth.M1',
'app03_phone_number_management.middleware.auth.M2',
]
class AuthMiddleware(MiddlewareMixin):
# return None就會執行下去
def process_request(self, request):
# 加上可以直接訪問的頁面:、
if request.path_info == "/login":
return
info_dict = request.session.get("info")
if info_dict:
return
#else:
# 這樣重定向會一直死循環報錯-->需要排除可以直接訪問的頁面
# 邏輯有點像物業需要你先證明業主身份才開門但是證明文件在裡面
# return redirect('/login/')
P54用戶注銷
def logout(request):
request.session.clear()
return redirect('/login/')