1.中间件的概念

中间件,是介于request与response处理之间的处理程序,相对比较轻量级,并且在全局上改变django的输入与输出。
因为改变的是全局,所以需要谨慎使用,否则会影响性能。
如果想修改views.py中的HttpRequest对象或HttpResponse对象,可以通过中间件来实现。

Django中默认的中间件
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',
]

2.自定义中间件

2.1中间件共有四个方法

process_request
process_view
process_exception
process_response

2.2自带中间件的process_request与process_response

当用户发起请求的时候,首先执行所有中间件的process_request函数。
之后到达views函数。
然后执行process_response函数。
最后返回给请求者。

下面是dajngo中的自带中间件,

9.中间件_第1张图片

2.3自定义中间件的process_request与process_response

settings.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',
    'app1.my_middleware.Md1',
    'app1.my_middleware.Md2',
]

views.py


from django.shortcuts import render,HttpResponse,redirect

def index(request):
    print("view函数")
    return HttpResponse("OK")

my_middleware.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse

class Md1(MiddlewareMixin):

    def process_request(self,request):
        print("Md1请求")

    def process_response(self,request,response):
        print("Md1返回")
        return response

class Md2(MiddlewareMixin):

    def process_request(self,request):
        print("Md2请求")
        #return HttpResponse("Md2中断")
    def process_response(self,request,response):
        print("Md2返回")
        return response

结果

Md1请求
Md2请求
view函数
Md2返回
Md1返回

9.中间件_第2张图片

如果在Md2中直接返回return HttpResponse("Md2中断"),程序将跳过views中的视图函数,直接执行中间件的process_response

结果为
Md1请求  
Md2请求  
Md2返回  
Md1返回

9.中间件_第3张图片

2.4process_view()函数

2.4.1process_view()

process_view(self, request, callback, callback_args, callback_kwargs)

my_middleware.py

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
class Md1(MiddlewareMixin):
    def process_request(self,request):
        print("Md1请求")
        #return HttpResponse("Md1中断")
    def process_response(self,request,response):
        print("Md1返回")
        return response
    def process_view(self, request, callback, callback_args, callback_kwargs):
        print("Md1view")
class Md2(MiddlewareMixin):
    def process_request(self,request):
        print("Md2请求")
        #return HttpResponse("Md2中断")
    def process_response(self,request,response):
        print("Md2返回")
        return response
    def process_view(self, request, callback, callback_args, callback_kwargs):
        print("Md2view")

运行结果

Md1请求
Md2请求
Md1view
Md2view
view函数
Md2返回
Md1返回

9.中间件_第4张图片

2.4.2process_view()调用视图函数

my_middleware.py

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
class Md1(MiddlewareMixin):
    def process_request(self,request):
        print("Md1请求")
        #return HttpResponse("Md1中断")
    def process_response(self,request,response):
        print("Md1返回")
        return response
    def process_view(self, request, callback, callback_args, callback_kwargs):
        print("Md1view")
        # 调用视图函数
        response = callback(request, *callback_args, **callback_kwargs)
        return response
class Md2(MiddlewareMixin):
    def process_request(self,request):
        print("Md2请求")
        #return HttpResponse("Md2中断")
    def process_response(self,request,response):
        print("Md2返回")
        return response
    def process_view(self, request, callback, callback_args, callback_kwargs):
        print("Md2view")

结果

Md1请求
Md2请求
Md1view
view函数
Md2返回
Md1返回

9.中间件_第5张图片

2.4.3process_view()中return HttpResponse

my_middleware.py

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
class Md1(MiddlewareMixin):
    def process_request(self,request):
        print("Md1请求")
        #return HttpResponse("Md1中断")
    def process_response(self,request,response):
        print("Md1返回")
        return response
    def process_view(self, request, callback, callback_args, callback_kwargs):
        print("Md1view")
# process_view中返回HttpResponse
        return HttpResponse("Md1view 中断")
class Md2(MiddlewareMixin):
    def process_request(self,request):
        print("Md2请求")
        #return HttpResponse("Md2中断")
    def process_response(self,request,response):
        print("Md2返回")
        return response
    def process_view(self, request, callback, callback_args, callback_kwargs):
        print("Md2view")

结果

Md1请求
Md2请求
Md1view
Md2返回
Md1返回

9.中间件_第6张图片

2.5process_exception()函数

2.5.1process_exception()

my_middleware.py

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse

class Md1(MiddlewareMixin):

    def process_request(self, request):
        print("Md1请求")
        # return HttpResponse("Md1中断")

    def process_response(self, request, response):
        print("Md1返回")
        return response

    def process_view(self, request, callback, callback_args, callback_kwargs):
        # return HttpResponse("hello")
        # response=callback(request,*callback_args,**callback_kwargs)
        # return response
        print("md1 process_view...")

    def process_exception(self, request, exception):
        print("md1 process_exception...")

class Md2(MiddlewareMixin):
    def process_request(self, request):
        print("Md2请求")
        # return HttpResponse("Md2中断")

    def process_response(self, request, response):
        print("Md2返回")
        return response

    def process_view(self, request, callback, callback_args, callback_kwargs):
        print("md2 process_view...")

    def process_exception(self, request, exception):
        print("md2 process_exception...")

views.py

from django.shortcuts import render,HttpResponse,redirect

def index(request):
    print("view函数")
    ui
    return HttpResponse("OK")

结果

Md1请求
Md2请求
md1 process_view...
md2 process_view...
view函数
md2 process_exception...
md1 process_exception...
Md2返回
Md1返回

9.中间件_第7张图片

2.5.2process_exception()中return HttpResponse

my_middleware.py

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse

class Md1(MiddlewareMixin):

    def process_request(self, request):
        print("Md1请求")
        # return HttpResponse("Md1中断")

    def process_response(self, request, response):
        print("Md1返回")
        return response

    def process_view(self, request, callback, callback_args, callback_kwargs):
        # return HttpResponse("hello")
        # response=callback(request,*callback_args,**callback_kwargs)
        # return response
        print("md1 process_view...")

    def process_exception(self, request, exception):
        print("md1 process_exception...")

class Md2(MiddlewareMixin):
    def process_request(self, request):
        print("Md2请求")
        # return HttpResponse("Md2中断")

    def process_response(self, request, response):
        print("Md2返回")
        return response

    def process_view(self, request, callback, callback_args, callback_kwargs):
        print("md2 process_view...")

    def process_exception(self, request, exception):
        print("md2 process_exception...")
                # 返回HttpResponse
        return HttpResponse("Md2exception中断")

结果

Md1请求
Md2请求
md1 process_view...
md2 process_view...
view函数
md2 process_exception...
Md2返回
Md1返回

9.中间件_第8张图片

2.6应用案例

1.做IP访问频率限制
某些IP访问服务器的频率过高,进行拦截,比如限制每分钟不能超过20次。

2.URL访问过滤
如果用户访问的是login视图(放过)
如果访问其他视图,需要检测是不是有session认证,已经有了放行,没有返回login,这样就省得在多个视图函数上写装饰器了!

尝试阅读
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',