python(Django 中间件)

中间件

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

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

与mange.py在同一目录下的文件夹 wupeiqi/middleware下的auth.py文件中的Authentication类

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

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对象,则直接将该对象返回给用户。

自定义中间件

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',
    'wupeiqi.middleware.auth.RequestExeute',
)

 

 

 

views:

#######################################

class Foo:
    def __init__(self,req,html,dic):
        self.req = req
        self.html = html
        self.dic = dic
    def render(self):
        # // 创建钩子
        return render(self.req,self.html,self.dic)

def test(request,nid):
    print('小姨妈-->没带钱')
    # return render(request, 'index.html', {...})
    return Foo(request, 'index.html', {'k1': 'v1'})

 

 

/Middle.m1

from django.utils.deprecation import MiddlewareMixin

class Row1(MiddlewareMixin):
    def process_request(self,request):
        print('王森')

    def process_view(self, request, view_func, view_func_args, view_func_kwargs):
        print('张欣彤')

    def process_response(self, request, response):
        print('扛把子')
        return response

from django.shortcuts import HttpResponse
class Row2(MiddlewareMixin):
    def process_request(self,request):
        print('程毅强')
        # return HttpResponse('走')

    def process_view(self, request, view_func, view_func_args, view_func_kwargs):
        print('张需要')

    def process_response(self, request, response):
        print('侯雅凡')
        return response

class Row3(MiddlewareMixin):
    def process_request(self,request):
        print('刘东')

    def process_view(self, request, view_func, view_func_args, view_func_kwargs):
        print('邵林')

    def process_response(self, request, response):
        print('连之泪')
        return response

    def process_exception(self, request, exception):
        if isinstance(exception,ValueError):
            return HttpResponse('出现异常》。。')

    def process_template_response(self,request,response):
        # 如果Views中的函数返回的对象中,具有render方法
        print('-----------------------')
        return response

utl.py

path('test/(?P<nid>\d+)$', views.test),

setting.py

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',

]

发表评论