Django之MIDDLEWARE 中间件

 

MIddel模块执行顺序:process_request->process_view->views函数->process_response

出现异常执行顺序:process_request->process_view->views函数出现异常->process_exception->process_response

注释:Django只能识别指定的方法名称

 

中间件中可以定义四个方法,分别是:

 

  • process_request(self,request)
  • process_view(self, request, callback, callback_args, callback_kwargs)
  • process_template_response(self,request,response)
  • process_exception(self, request, exception)
  • process_response(self, request, response)

以上方法的返回值可以是None和HttpResonse对象,如果是None,则继续按照django定义的规则向下执行,如果是HttpResonse对象,则直接将该对象返回给用户。

 

 

 

 

 

# -*- coding:utf-8 -*-
# author:

from django.utils.deprecation import MiddlewareMixin
class Row1(MiddlewareMixin):
    def process_request(self,request):
        print('管道1')

    def process_view(self,request, view_func,view_func_args,view_func_kwargs ):
        print('出来了1')

    def process_response(self, request, response):
        print('管道进行中3')
        return response
from django.shortcuts import HttpResponse
class Row2(MiddlewareMixin):
    def process_request(self,request):
        print('管道2')
        # return HttpResponse('跑')
    def process_view(self,request, view_func,view_func_args,view_func_kwargs ):
        print('出来了2')

    def process_response(self, request, response):
        print('管道进行中2')
        return response

class Row3(MiddlewareMixin):
    def process_request(self,request):
        print('管道3')

    def process_view(self,request, view_func,view_func_args,view_func_kwargs ):
        print('出来了3')

    def process_response(self,request,response):
        print('管道进行中1')
        return response

    def process_exception(self, request, exception):#对views报错进行处理

        return HttpResponse('出现异常...')
    def process_template_response(self,request,response):
        #如果views中的函数返回对象中,具有render方法
        print('--------render----------')
        return HttpResponse('----憨批-----')

setting中配置:

在django项目的settings模块中,有一个 MIDDLEWARE_CLASSES 变量,其中每一个元素就是一个中间件,如下图。

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',
    'Middle.m1.Row1',
    'Middle.m1.Row2',
    'Middle.m1.Row3',#根据点来进入下一级
]

 

posted @ 2021-06-04 14:56  安好_世界  阅读(65)  评论(0编辑  收藏  举报