• Python


    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,程序就继续执行后续的中间件了

  • 相关阅读:
    友链
    二维码相关学习一
    Nginx 反向代理location与proxy_pass配置规则总结
    redis分布式锁应用
    接口跨域如何验证
    阿里人都在使用的在线诊断工具—Arthas
    JVM: GC过程总结(minor GC 和 Full GC)
    JVM模型
    第三方网站不加载微信公众号的图片解决方案
    bat2exe
  • 原文地址:https://www.cnblogs.com/sch01ar/p/11514563.html
Copyright © 2020-2023  润新知