Middleware supplement :
Self written middleware should be in setting Registered in the , Execute in the order of registration ,
Request to come in and execute once , Return the response to execute once
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
class M1(MiddlewareMixin):
def process_request(self, request):
print("M1 Came in ")
# no return value , by None You can keep going
return HttpResponse(" No access ")
def process_response(self, request, response):
print("M1 go ")
return response
class M2(MiddlewareMixin):
def process_request(self, request):
print("M2 Came in ")
def process_response(self, request, response):
print("M2 go ")
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 It's going to go on
def process_request(self, request):
# Plus directly accessible pages :、
if request.path_info == "/login":
return
info_dict = request.session.get("info")
if info_dict:
return
#else:
# In this way, the redirection will always report errors in an endless loop --> You need to exclude pages that can be accessed directly
# The logic is a bit like that the property requires you to prove the identity of the owner before opening the door, but the supporting documents are inside
# return redirect('/login/')
P54 User logout
def logout(request):
request.session.clear()
return redirect('/login/')