这是Django1.11.7版本的使用方法
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
LOGIN_REQUIRE_PATHS=[
'/app/mine/',
'/app/goods/',
]
class MyappMiddleware(MiddlewareMixin):
def process_request(self,request):
path=request.path
usession=request.session.get('uname',None)
if path in LOGIN_REQUIRE_PATHS and not usession:
return redirect(reverse('app:login'))
def process_view(self, request, view_func, view_args, view_kwargs):
pass
def process_template_response(self, request, response):
pass
def process_response(self, request, response):
pass
def process_exception(self, request, exception):
return redirect('/')
最后在settings中注册中间件
MIDDLEWARE = [
'MyMiddleWare.myMiddleWare.MyAppMiddleWare'
]