Python - Django - 中间件 process_request

process_request 函数是中间件在收到 request 请求之后执行的函数

该函数的执行顺序是按照 settings.py 中中间件的配置顺序执行的

如果该函数返回 None,继续执行后面的中间件的 process_request 方法

如果该函数返回 response,则不再继续执行后面的中间件的 process_request 方法

middleware_test.py:

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

allow_url = ["/admin/", "/news/", "/uploads/"]


class Test(MiddlewareMixin):
    def process_request(self, request):
        print("这是一个中间件 --> test")


class Test2(MiddlewareMixin):
    def process_request(self, request):
        print("这是一个中间件 --> test2")
        if request.path_info in allow_url:
            return
        else:
            return HttpResponse("这里是 HttpResponse")

views.py:

from django.shortcuts import HttpResponse


def index(request):
    print("这里是 index 页面")
    return HttpResponse("这里是主页面 index")

访问,http://127.0.0.1:8000/index/

 

运行结果:

 

只执行到 Test2 这个中间件,没有再执行 Test1 这个中间件,因为 Test2 返回了 response

如果访问,http://127.0.0.1:8000/admin/

 

中间件 Test1 也执行了,因为访问的 url 在 allow_url 内,所以 process_request 返回了一个 None,程序就继续执行后续的中间件了

posted @ 2019-09-12 18:33  Sch01aR#  阅读(2723)  评论(0编辑  收藏  举报