首页 > 代码库 > Django基础之中间件

Django基础之中间件

一:中间件

中间件:django 中的中间件(middleware),在django中,就是一个类、在请求来和结束后,Django会根据自己的规则在合适的时机执行中间件的相应方法;

应用:对所有请求或一部分请求做批量处理;
在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,
]
如图↓

1、中间件可以定义的五个方法:

            process_request(self,request)
            
            process_response(self,request,response)
                必须有返回值
                return response
                
            process_view(self, request, callback, callback_args, callback_kwargs)
            process_exception(self,request,exception)
            process_template_view(self,request,response)
            
            以上方法的返回值可以是None和HttpResonse对象,如果是None,则继续按照
            Django定义的规则向下执行,如果是HttpResonse对象,则直接将该对象返回给用户;

二:自定义中间件

1、创建中间件类:
class RequestExeute(object):
      
    def process_request(self,request):
        pass
    def process_view(self, request, callback, callback_args, callback_kwargs):
        i =1
        pass
    def process_exception(self, request, exception):
        pass
      
    def process_response(self, request, response):
        return response

2、注册中间件

MIDDLEWARE_CLASSES = (
    ‘django.contrib.sessions.middleware.SessionMiddleware‘,
    ‘django.middleware.common.CommonMiddleware‘,
    ‘django.middleware.csrf.CsrfViewMiddleware‘,
    ‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
    ‘django.contrib.auth.middleware.SessionAuthenticationMiddleware‘,
    ‘django.contrib.messages.middleware.MessageMiddleware‘,
    ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
    ‘xiaoxiaoxiao.middleware.auth.RequestExeute‘,
)

Django基础之中间件