• Python


    中间件简介:

    中间件是在 wsgi.py 之后,urls.py 之前,在全局操作 Django 请求和响应的模块

    在 settings.py 中可以看到中间件的相关配置

    该列表中的每一个元素都是一个类,一个中间件

    例如:

    django.middleware.csrf.CsrfViewMiddleware
    可以写为:
    from django.middleware.csrf import CsrfViewMiddleware
    

    中间件的处理顺序就是按照该列表元素的顺序进行处理

    中间件中可以定义 5 个方法:

    process_request(self, request)
    process_response(self, request, response)
    process_view(self, request, view_func, view_args, view_kwargs)
    process_template_response(self, request, response)
    process_exception(self, request, exception)
    

    自定义中间件:

    在根目录下新建一个 middleware_test.py 文件

    middleware_test.py:

    from django.utils.deprecation import MiddlewareMixin
    
    
    class Test(MiddlewareMixin):
        def process_request(self, request):
            print("这是一个中间件 --> test")
    
    
    class Test2(MiddlewareMixin):
        def process_request(self, request):
            print("这是一个中间件 --> test2")
    

    在 settings.py 的中间件配置中添加自定义的中间件

    这里先添加 Test2,再添加 Test,所以会先执行 Test2,再执行 Test

    views.py:

    from django.shortcuts import HttpResponse
    
    
    def index(request):
        print("这里是 index 页面")
        return HttpResponse("这里是主页面 index")
    

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

    看一下 pycharm 打印了什么

    先执行了中间件 Test2,然后再执行 Test1,最后执行的是 views.py 中的 index 函数

  • 相关阅读:
    configbody
    add log to ldap
    registerComponent announceExist
    ldap
    6485 commands
    Titled Motor Entry
    ldap pkg
    remove rpm pkg
    创建自定义验证控件,以验证多行文本框中内容长度为例
    ASP.NET利用CustomValidator的ClientValidationFunction与OnServerValidate来double check资料输入的正确性
  • 原文地址:https://www.cnblogs.com/sch01ar/p/11508002.html
Copyright © 2020-2023  润新知