Python - Django - 中间件 process_request

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

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

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

若是该函数返回 response,则再也不继续执行后面的中间件的 process_request 方法url

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:blog

from django.shortcuts import HttpResponse


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

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

 

运行结果:class

 

只执行到 Test2 这个中间件,没有再执行 Test1 这个中间件,由于 Test2 返回了 responsetest

若是访问,http://127.0.0.1:8000/admin/import

 

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

相关文章
相关标签/搜索