Django中间件

1.中间件概述:

①在setting中的如下所示即为中间件,所有请求来了都要走中间件:

②流程:请求先走中间件,然后转发到url中,url转发给视图处理,然后走中间件,最后转发给响应

image-20200620203921460

2.自定义中间件:

①在项目下新建一个目录,然后新建一个类,类里面写中间件

from django.utils.deprecation import MiddlewareMixin


class MD1(MiddlewareMixin):
      #只接受request请求
    def process_request(self,request):
        print('MD1')
      #只接受response响应,必须 return response
    def process_response(self, request, response):
        print('MD1 结束')
        return response

②在settings文件中配置中间件

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.utils.mymiddleware.MD1',
]

3.Django请求生命周期流程:

image-20200620211639099

4.如果中间件中process_request返回一个HttpResponse对象,则不会走后面的流程:

class MD1(MiddlewareMixin):
      #只接受request请求
    def process_request(self,request):
        print('MD1')
        return HttpResponse('结束')

5.白名单:

posted @ 2020-06-20 22:18  小凡2019  阅读(74)  评论(0编辑  收藏  举报